【发布时间】:2021-03-03 16:27:13
【问题描述】:
我有一个非常简单的函数:
function foo<T>(input: T, def: T) : T {
return !!input ? input : def;
}
这么叫
foo(6, 7);
foo("h", "i")
没问题。
现在如果我改成
function foo<T>(input: T | null | undefined, def: T) : T {
return !!input ? input : def;
}
我收到类似“类型 '6' 的参数不能分配给类型 '7 | null | undefined' 的参数。”和“类型 '“h”' 的参数这样的错误不能分配给“i”| null | undefined'类型的参数。“
但如果我这样称呼它
const h: string = "h";
const i: string = "i";
foo(h, i);
那么就OK了。
这是为什么呢?
【问题讨论】:
-
为什么在 or 条件中添加 null 和 undefined ?我认为它被视为单个字符串变量类型。
-
@Terry 你真快!是的,它似乎只在早期版本上?
-
你使用的是哪个版本的 TS?
标签: typescript