我有这个通用方法
class Foo {
public static bar<T>(x: T): T {
...
if(x === null)
return null; //<------- syntax error
...
}
}
... //somewhere
const x = Foo.bar<number | null>(1);
我收到语法错误
TS2322: Type 'null' is not assignable to type 'T'.
我期待这个编译,因为
T
可能是 null
.解决这个问题的正确方法是什么
最佳答案
您必须将返回类型声明为 null
或关闭 strictNullChecks
在你的 tsconfig
public static bar<T>(x: T): T | null
或者你可以输入 null
as any
例如 return null as any;
关于typescript - 类型 'null' 不可分配给类型 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715119/