【发布时间】:2017-09-22 03:28:25
【问题描述】:
使用 typescript 2.5.2 以下代码无法使用 strictNullChecks 编译:
function ifnull<T>(x: T | null | undefined, def: T): T
{
return x != null ? x : def;
}
console.log(ifnull(2, 1));
给出错误:
Argument of type '2' is not assignable to parameter of type '1 | null | undefined'.
它似乎推断 T 是 1 而不是数字。当您在没有 strictNullChecks 的情况下进行编译时,它会正确推断出类型 number。我没有足够的信心知道这是 Typescript 中的错误还是预期的行为,所以我更愿意在填写错误报告之前在这里询问。
这是预期的吗?严格推理的基本原理是什么,有没有办法定义 ifnull 而不必将其称为 ifnull<number>(...) 或 ifnull<string>(...)?
【问题讨论】:
标签: typescript