JavaScript:我可以以某种方式强类型函数参数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9789752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: can I somehow strong type function parameters?
提问by BuZz
I am a newbie with JavaScript and I feel the unresistible need to strong type my functions parameters for a couple of tools I am coding:
我是 JavaScript 的新手,我觉得需要为我正在编码的几个工具强类型我的函数参数:
- That would give me autocompletion within those functions
- Debugging/function access gets more consistent
- 这会让我在这些函数中自动完成
- 调试/功能访问变得更加一致
After some googling, I guess this isn't directly possible. However, are there common tools to emulate this rather simply?
经过一些谷歌搜索,我想这不是直接可能的。但是,是否有通用工具可以相当简单地模拟这一点?
What are your thoughts?
你觉得呢?你有没有什么想法?
采纳答案by Daff
No, you can't and even if there is a way you shouldn't. JavaScript is a dynamically typed language. For auto completion you can however use JSDocstyle documentation tags that give some type pointers:
不,你不能,即使有你不应该的方式。JavaScript 是一种动态类型语言。但是,对于自动完成,您可以使用JSDoc样式的文档标签,这些标签提供一些类型指针:
var Person = {
/**
* Say hi
* @param {String} name The name to say hi to
* @return {String}
*/
sayHi : function(name)
{
return 'Hi ' + name;
}
}
If they are being used depends entirely on your IDE though.
是否使用它们完全取决于您的 IDE。
回答by FloatOverflow
People writing "you shouldn't use it" are wrong. In the next Java Script 2.x specification there is a plan to add strong typed variables.
写“你不应该使用它”的人是错误的。在下一个 Java Script 2.x 规范中,计划添加强类型变量。
Meanwhile you may use very simple solution to emulate strong types:
同时,您可以使用非常简单的解决方案来模拟强类型:
var = Object.create( String );
After that autocompleting in a lot of IDE (including IntelliJ IDEA) will work great and you have declared and initialized an object of specified type.
之后,在许多 IDE(包括 IntelliJ IDEA)中自动完成会很好用,并且您已经声明并初始化了一个指定类型的对象。
Read more on my blog.
在我的博客上阅读更多内容。
回答by Ryan Knell
Have you looked at Typescript? Its an open source project by Microsoft that allows you to develop using strong typing and then compiles the code into Javascript. I know is Microsoft but take a look before you dismiss it.
你看过打字稿吗?它是 Microsoft 的一个开源项目,允许您使用强类型进行开发,然后将代码编译为 Javascript。我知道是微软,但在你驳回它之前先看看。
http://www.typescriptlang.org/
http://www.typescriptlang.org/
Edit 2017
编辑 2017
There are now two big players on this scene, Typescript (as suggested above) has been battle proven and is now used extensively by Angular 2. If structure and fairly rigid typing if what you are looking for, that is your best bet.
现在这个场景中有两个大玩家,Typescript(如上所述)已经过战斗证明,现在被 Angular 2 广泛使用。如果你正在寻找结构和相当严格的打字,那是你最好的选择。
Another option is Flow (https://flow.org/) it was developed by Facebook and is used by them heavily in React. Flow allows you to only specify which files you want to type check and is a lower barrier to entry IMO.
另一种选择是 Flow(https://flow.org/),它是由 Facebook 开发的,在 React 中被他们大量使用。Flow 允许您仅指定要键入检查的文件,并且是进入 IMO 的较低门槛。
It is worth saying that adding type checking adds a fair amount of complexity to your build process - it requires you to have a build process!
值得一提的是,添加类型检查为您的构建过程增加了相当多的复杂性——它需要您有一个构建过程!
回答by DCoder
Have you looked at Google Closure Compiler?
Certain IDEs (like Jetbrains' products) try to understand JSDoc and help out, but sometimes their annotation parser conflicts with Google Closure's. However, even with Closure you're not gonna get perfect strong typing.
某些 IDE(如 Jetbrains 的产品)试图理解 JSDoc 并提供帮助,但有时它们的注释解析器与 Google Closure 的冲突。但是,即使使用 Closure,您也不会获得完美的强类型。
Also, it might be overkill, but look at Haxe.
回答by MatuDuke
JavaScript recognizes the following types of values:
JavaScript 识别以下类型的值:
Numbers: such as 42 or 3.14159
数字:例如 42 或 3.14159
Logical (Boolean): values either true or false
逻辑(布尔):值为真或假
Strings: such as "Howdy!"
字符串:例如“你好!”
null: a special keyword denoting a null value; null is also a primitive value. Because JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant
null:表示空值的特殊关键字;null 也是一个原始值。由于 JavaScript 区分大小写,因此 null 与 Null、NULL 或任何其他变体不同
undefined: a top-level property whose value is undefined; undefined is also a primitive value.
undefined:其值未定义的顶级属性;undefined 也是一个原始值。
There is no explicit distinction between integer and real-valued numbers[...]
整数和实数值之间没有明确的区别[...]
JavaScript is a dynamically typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution
JavaScript 是一种动态类型语言。这意味着您在声明变量时不必指定其数据类型,并且在脚本执行期间会根据需要自动转换数据类型
From https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals
来自https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals
So, no, you can't use strong type in JavaScript
所以,不,你不能在 JavaScript 中使用强类型
回答by Tom
no you can't; javascript is a weakly typed language. This means that JavaScript will figure out what type of data you have.
不,你不能;javascript 是一种弱类型语言。这意味着 JavaScript 将确定您拥有的数据类型。
回答by colxi
You can implement a system that handles the type checks automatically, using a wrapper in your function.
您可以在您的函数中使用包装器来实现一个自动处理类型检查的系统。
With this approach, you can build a complete
declarative type check system
that will manage for you the type checks . If you are interested in taking a more in depth look at this concept, check the Functyped library
使用这种方法,您可以构建一个完整的
declarative type check system
来为您管理类型检查。如果您有兴趣更深入地了解这个概念,请查看Functyped 库
The following implementation illustrates the main idea, in a simplistic, but operative way:
以下实现以简单但可操作的方式说明了主要思想:
/*
* checkType() : Test the type of the value. If succeds return true,
* if fails, throw an Error
*/
function checkType(value,type, i){
// perform the appropiate test to the passed
// value according to the provided type
switch(type){
case Boolean :
if(typeof value === 'boolean') return true;
break;
case String :
if(typeof value === 'string') return true;
break;
case Number :
if(typeof value === 'number') return true;
break;
default :
throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);
}
// test didn't succeed , throw error
throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);
}
/*
* typedFunction() : Constructor that returns a wrapper
* to handle each function call, performing automatic
* arguments type checking
*/
function typedFunction( parameterTypes, func ){
// types definitions and function parameters
// count must match
if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);
// return the wrapper...
return function(...args){
// provided arguments count must match types
// definitions count
if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);
// iterate each argument value, and perform a
// type check against it, using the type definitions
// provided in the construction stage
for(let i=0; i<args.length;i++) checkType( args[i], parameterTypes[i] , i)
// if no error has been thrown, type check succeed
// execute function!
return func(...args);
}
}
// Play time!
// Declare a function that expects 2 Numbers
let myFunc = typedFunction( [ Number, Number ], (a,b)=>{
return a+b;
});
// call the function, with an invalid second argument
myFunc(123, '456')
// ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2
回答by lewdev
You should look into compiling your work using "ADVANCED_OPTIMIZATIONS" in Google Closure Compiler which will do type checking of your arguments or variables.
您应该考虑在 Google Closure Compiler 中使用“ADVANCED_OPTIMIZATIONS”来编译您的工作,这将对您的参数或变量进行类型检查。
Annotating JavaScript for the Closure Compiler: Type Expressions
Example data types:boolean, Window, goog.ui.Menu, string, number
示例数据类型:boolean、Window、goog.ui.Menu、string、number
Here's an example of declaring a variable and its data type. If you try to set the variable into another data type, it will give you an error or warning message after compiling.
这是一个声明变量及其数据类型的示例。如果您尝试将变量设置为另一种数据类型,则编译后会给出错误或警告消息。
/**
* The message hex ID.
* @type {string}
*/
var hexId = hexId;
Here is an example of a class declaration with possible parameter types:
下面是一个带有可能参数类型的类声明示例:
/**
* Some class, initialized with an optional value.
* @param {Object=} opt_value Some value (optional).
* @constructor
*/
function MyClass(opt_value) {
/**
* Some value.
* @type {Object|undefined}
*/
this.myValue = opt_value;
}
Using the "ADVANCED_OPTIMIZATIONS," makes you write JavaScript a little more properly since it also gives some link
使用“ADVANCED_OPTIMIZATIONS”可以让你更正确地编写 JavaScript,因为它还提供了一些链接