首页 > 解决方案 > 为什么 TypeScript 仍然认为我的变量赋值可能为 null

问题描述

我正在尝试使用具有可为空成员的类型来扩展另一种成员永远不会为空的类型。

如果我这样做:

type Foo = {
    a: string | null
    b: string | null
}

type Bar = {
    a: string
    b: string
    c: string
}

const foo: Foo = {
    a: 'A',
    b: 'B',
}

const bar: Bar = {
    ...foo,
    c: 'C',
}

TypeScript 会抱怨,告诉我参考 'bar' 变量,'Type null is notassignable to type string'。说“a”和“b”可能为空。

我会认为,由于赋值太 'foo' 没有空值,所以 bar 赋值也不能有任何空值。

在我的用例中,“foo”和“bar”都是测试的一部分,我正在测试 foo 的属性不为空的路径。我可以删除“Foo”注释,这会起作用,但我在编写测试时需要编辑器的帮助。此外,如果我稍后添加到 'Foo' 或 'Bar' 类型,我希望 typescript 在我的测试编译时告诉我,而不是我的测试失败,或者更糟糕的是,没有失败。像这样的事情是可能的还是我以错误的方式解决这个问题?

标签: typescript

解决方案


我认为编译器不是查看分配,而是查看类型声明。

另一方面,您通过使用 来混合苹果和橙子...foo。我会像这样重写它,作为副作用,它还消除了您遇到的错误:

interface Foo {
    a: string | null
    b: string | null
}

interface Bar extends Foo {
    c: string
}

const foo: Foo = {
    a: 'A',
    b: 'B',
}

const bar: Bar = {
   ...foo,
   c: 'C',
}

但另一方面,如果FooBar根本不相关,而你需要这个只是为了智能,我会保留你已经拥有的,然后在...foo as any里面添加bar


推荐阅读