我有这种通用方法
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:类型“ null”不可分配给类型“ T”。
我希望它可以编译,因为T
可能是null
。
解决此问题的正确方法是什么
您必须在tsconfig中将返回类型声明为null
或关闭strictNullChecks
public static bar<T>(x: T): T | null
或者您可以输入nullas any
例如
return null as any;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句