[英]Types of optional and default parameters in typescript
假设我正在制作一个可以返回唯一参数的函数,在javascript中,它将像:
function returnItself(x) {
return x;
}
而且我还想保持参数的类型不变,并使参数成为可选参数,所以我写道:
function returnItself<T>(x?: T) {
return x;
}
但是结果是...
var a1 = returnItself("foo");
type A1 = typeof a1; // expect A1 to be "string", but it's "string | undefined".
var a2 = returnItself();
type A2 = typeof a2; // expect A2 to be "undefined", but it's "{} | undefined".
我试图将可选参数更改为默认值:
function returnItself<T extends any>(x: T = 0 as number) {
return x; // if x is not given it should return number 0;
}
但是,甚至出现了编译器错误:
Type 'number' is not assignable to type 'T'.
写这个的正确方法是什么?
*****编辑****
在这种情况下:
function returnItself<T>(x?: T) {
return x;
}
var a1 = returnItself(undefined); // a1 = undefined. ok
var a2 = returnItself(); // a2 = undefined. ok
type A1 = typeof a1; // type A1 = undefined. ok
type A2 = typeof a2; // type A2 = {} | undefined. ???
如果我清楚地将undefined作为参数传递,则Typescript可以正确推断返回类型。
但是,当我只是不给出参数时,我期望与上面的结果相同的结果(和类型),但它们的结果类型不相同。
我相信returnItself()
和returnItself(undefined)
应该具有相同的行为,也许我错了?
可选意味着它可以是undefined
或null
。 所以返回的类型是正确的。
如果您不希望它为null,则只需使用
function returnItself<T>(x: T) {
return x;
}
T
是泛型类型,这意味着它可以是任何东西。 您不能强迫它成为number
您不能为T
分配number
,因为它对编译器没有意义。 基本上, T
是泛型类型,您在这里将其用作变量。 这意味着调用此函数的用户可以在运行时说出类型T
应该是什么:
const a1 = returnItself<number>(9)
因此,当您将number
分配给T
打字稿时会抱怨,因为它尚不知道T
是什么。 如果您想在TypeScript
使用可选值,建议您养成显式检查该值是否存在于函数主体中的习惯。 以下内容将通过您的所有测试:
function returnItself<T>(x?: T) {
if (x) return x
else return 0 //or whatever other value you want as a default case
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.