typescript 2.0:具有默认值的参数(typescript 2.0: parameters with default values)

编程入门 行业动态 更新时间:2024-10-09 16:24:40
typescript 2.0:具有默认值的参数(typescript 2.0: parameters with default values)

地狱伙计们,

这是另一个打字稿2.0问题(启用了严格的空检查模式)。 因此,如果您定义一个具有所有参数的默认值的函数:

(name = "Luis", age = 40)=>void

然后所有参数都被认为是可选的,即,就好像我们有以下签名:

(name?: string, age?: number) => void

对? 现在,当我们有这个签名时会发生什么:

(name = "Luis", age: number ) => void

根据VS代码,该签名与以下内容兼容:

(name: string, age: string) => void

现在,如果我激活严格的空检查模式,则以下调用不应该产生错误:

doIt(undefined, 30);

它编译好了,但如果我没错,undefined只会自动添加到可选参数类型列表中。 我没有找到任何默认初始化参数的引用。

所以,如果以前的电话没问题,有人可以指点我在官方文档中找到相关信息吗?

谢谢,

路易斯

Hell guys,

Here's another typescript 2.0 question (with strict null check mode enabled). So, if you define a function which has default values for all parameters:

(name = "Luis", age = 40)=>void

Then all parameters are considered optional, ie, it's as if we have the following signature:

(name?: string, age?: number) => void

Right? Now, what happens when we have this signature:

(name = "Luis", age: number ) => void

According to VS code, that signature is compatible with:

(name: string, age: string) => void

Now, if I activate the strict null check mode, shouldn't the following call produce an error:

doIt(undefined, 30);

It compiles ok, but if I'm not wrong, undefined will only get added automatically to the list of types of optional parameters. I haven't found any references to default initialized parameters.

So, if the previous call is ok, can someone point me to where I can find info about it in the official docs ?

Thanks,

Luis

最满意答案

快速注意:您不能仅在签名中指定默认值,例如以下是错误:

declare var foo: (name = "Luis", age = 40) => void; // ERROR: defaults only allowed in implementation

继续以下代码:

var foo = (name = "Luis", age: number) => null; foo(undefined, 123); foo(null, 123); // ERROR

显示该name与string或undefined兼容。 工具提示错误,但一般分析是正确的。

请随时通过https://github.com/Microsoft/TypeScript/issues提出问题

Quick note: You cannot specify defaults in just signatures e.g. the following is an error:

declare var foo: (name = "Luis", age = 40) => void; // ERROR: defaults only allowed in implementation

Continuing the following code:

var foo = (name = "Luis", age: number) => null; foo(undefined, 123); foo(null, 123); // ERROR

Shows that the name is compatible with string or undefined. The tooltip is wrong but the general analysis is correct.

Feel free to raise an issue at https://github.com/Microsoft/TypeScript/issues

更多推荐

本文发布于:2023-08-04 19:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422331.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   参数   typescript   default   parameters

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!