是否有一种方法可以让javascript函数知道某个参数是某个类型的?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢你!
更新:作为答案是一个响亮的“不”,如果我想myDate被视为一个日期(为了在它上调用日期函数),我必须将其转换为函数内的日期或设置一个日期类型的新变量?
是否有一种方法可以让javascript函数知道某个参数是某个类型的?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢你!
更新:作为答案是一个响亮的“不”,如果我想myDate被视为一个日期(为了在它上调用日期函数),我必须将其转换为函数内的日期或设置一个日期类型的新变量?
当前回答
这可以很容易地用ArgueJS完成:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};
其他回答
TypeScript是目前最好的解决方案之一。
TypeScript通过向语言中添加类型来扩展JavaScript。
Typescript版本演示
// type alias
type myDateType = Date;
type myStringType = string;
function myFunction(myDate: myDateType, myString: myStringType) {
// do stuff
console.log(`myDate =`, myDate);
console.log(`myString =`, myString);
}
myFunction(new Date(), 'TypeScript is awesome!');
试试这个在线游乐场
refs
https://www.typescriptlang.org/
虽然不能将类型通知JavaScript语言,但可以通知IDE,因此可以获得更有用的自动补全。
这里有两种方法:
Use JSDoc, a system for documenting JavaScript code in comments. In particular, you'll need the @param directive: /** * @param {Date} myDate - The date * @param {string} myString - The string */ function myFunction(myDate, myString) { // ... } You can also use JSDoc to define custom types and specify those in @param directives, but note that JSDoc won't do any type checking; it's only a documentation tool. To check types defined in JSDoc, look into TypeScript, which can parse JSDoc tags. Use type hinting by specifying the type right before the parameter in a /* comment */: This is a pretty widespread technique, used by ReactJS for instance. Very handy for parameters of callbacks passed to 3rd party libraries.
打印稿
对于实际的类型检查,最接近的解决方案是使用TypeScript,它是JavaScript的超集。这里是5分钟内的TypeScript。
我假设您允许IDE帮助您;那么下面的答案可能会帮助你。
IDE: jetbrains/Golang如果你的IDE不是这个也没关系。我相信所有支持JSDoc的IDE都能满足您的大部分需求。
它可以很好地显示JSDoc。
Demo
我的- pkg base64编码- js。
/**
* Convert string to the base64 format.
*
* @param str {string} Input string
* @returns {string} some message about return...
* @example
* - btoa(toBinary("☸☹☺☻☼☾☿"))
* - Str2base64("☸☹☺☻☼☾☿")
* @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa#unicode_strings
*/
export function Str2base64(str) {
return btoa(toBinary(str))
}
. js
import * as base64 from "../pkg/encoding/base64"
const filenameB64 = base64.Str2base64("test")
有用的JSDoc文档
JSDoc块标签 显示@returns, @param, @type…
其他链接
jetbrains JSDoc /评论
不是在JavaScript本身,而是使用谷歌闭包编译器的高级模式,你可以做到:
/**
* @param {Date} myDate The date
* @param {string} myString The string
*/
function myFunction(myDate, myString)
{
//do stuff
}
参见https://code.google.com/closure/compiler/docs/js-for-compiler.html
使用typeof或instanceof:
const assert = require('assert');
function myFunction(Date myDate, String myString)
{
assert( typeof(myString) === 'string', 'Error message about incorrect arg type');
assert( myDate instanceof Date, 'Error message about incorrect arg type');
}