类型 'null' 不能分配给类型 'T' [英] Type 'null' is not assignable to type 'T'

查看:163
本文介绍了类型 'null' 不能分配给类型 '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'.

TS2322: Type 'null' is not assignable to type 'T'.

我希望它能够编译,因为 T 可能是 null.

I'm expecting this to compile because T could be null.

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

what is the proper way to solve this problem

推荐答案

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

You have to declare the return type as null or turn off strictNullChecks in your tsconfig

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

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

or you could type null as any e.g.

 return null as any;

这篇关于类型 'null' 不能分配给类型 'T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆