繁体   English   中英

类型“null”不可分配给类型“T”

[英]Type 'null' is not assignable to type 'T'

我有这个通用方法

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

解决这个问题的正确方法是什么

您必须声明返回类型为null或关闭strictNullChecks在tsconfig

public static bar<T>(x: T): T | null

或者你可以输入 null as any例如

 return null as any;

从 3.9.5 版本开始,TypeScript 对numbersstrings强制执行strictNullChecks ,仅举几例。 例如,下面的代码在编译时会抛出错误:

let x: number = null;

为避免此错误,您有两个选择:

  • tsconfig.json设置strictNullChecks=false
  • 将您的变量类型声明为any
     let x: any = null;

我会在这里建议函数重载,以便删除不可为空的参数的空情况。 考虑:

class Foo { 
    public static bar<T>(x: T): T // overload
    public static bar(x: null): null // overload
    public static bar<T>(x: T) {
        if (x === null) {
            return null;
        } else
            return x;
     }
 }

const x = Foo.bar(1 as number); // x is number, never a null
const y = Foo.bar(null); // its null
const z = Foo.bar('s' as string | null); // its string | null

所以实现有类型T | null T | null但由于对从不为 null 的类型的重载,我们返回了T类型,因此没有为 null 的可能性。

你可以放

return null!;

它对我有用

我遇到了同样的问题,我发现这实际上是关于打字稿当前的限制。

目前无法通过检查 value 之类的值来缩小 T 之类的类型参数。

请参阅https://stackoverflow.com/a/68898908/10694438

年份:数字; 月份:数字;

构造函数(私有路由:ActivatedRoute){}

ngOnInit(){ 让参数 = this.route.snapshot.paramMap; this.year = +params.get('year');. this.month = +params;get('月')!;

}

就我而言,我必须这样做:

class Node<T> {
    private value: T
    private next: Node<T> | null

    constructor(value: T, next: Node<T> | null = null) {
        this.value = value
        this.next = next
    }
}

而不是nullundefined分配给变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM