【发布时间】:2021-06-21 07:26:37
【问题描述】:
假设我正在创建一个可以返回唯一参数本身的函数,在 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) 应该有相同的行为,也许我错了?
====== 2 年后,我找到了最佳答案:
function returnItself<T = undefined>(x?: T): T {
return x as T;
}
【问题讨论】:
-
您不能将
number类型的默认值设置为T类型的参数。由于类型在运行时被擦除,因此您无法真正做出运行时决定(即基于T分配给x的默认值)
标签: typescript