typescript - 类型 'null' 不可分配给类型 'T'

标签 typescript

我有这个通用方法

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/

相关文章:

typescript - 'false' 是 TypeScript 中的有效返回类型吗?

typescript :类方法名称作为参数

javascript - 呈现 View 后使用 aurelia 将数据动态添加到页面

TypeScript Exclude<UnionOfTypes, Interface> 是类型 "never"

reactjs - 类型 '{}' 上不存在属性

macos - 无法在 MacOS 上安装 TypeScript - 终端错误

angular - 如何在 Angular 的规范测试文件中禁用strictNullChecks?

javascript - Typescript if and if not with boolean 和 string

angular - 在另一个服务 Angular 2 中注入(inject)服务

javascript - 在组件中添加外部 JS 文件以使用 Angular 2 在浏览器中渲染图像