我有这个通用方法
class Foo {
public static bar<T>(x: T): T {
...
if(x === null)
return null; //<------- syntax error
...
}
}
... //somewhere
const x = Foo.bar<number | null>(1);
Run Code Online (Sandbox Code Playgroud)
我收到语法错误
TS2322:类型“null”不可分配给类型“T”。
我期待这个编译,因为T可能是null.
解决这个问题的正确方法是什么
Mur*_*göz 102
您必须在 tsconfig 中声明返回类型为null或关闭strictNullChecks
public static bar<T>(x: T): T | null
Run Code Online (Sandbox Code Playgroud)
或者你可以输入 nullas any例如
return null as any;
Run Code Online (Sandbox Code Playgroud)
Ham*_*fri 24
自从3.9.5版本,打字稿强制执行strictNullChecks的numbers,并strings只是仅举几例。例如,下面的代码在编译时会抛出错误:
let x: number = null;
Run Code Online (Sandbox Code Playgroud)
为避免此错误,您有两个选择:
strictNullChecks=false在tsconfig.json.any:
let x: any = null;
Run Code Online (Sandbox Code Playgroud)
Oma*_* RB 18
你可以把
return null!;
Run Code Online (Sandbox Code Playgroud)
这对我有用
| 归档时间: |
|
| 查看次数: |
88935 次 |
| 最近记录: |