typescript - 为什么 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 在我的测试编译时告诉我,而不是我的测试失败,或者更糟糕的是,没有失败。像这样的事情是可能的还是我以错误的方式解决这个问题?
解决方案
我认为编译器不是查看分配,而是查看类型声明。
另一方面,您通过使用 来混合苹果和橙子...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',
}
但另一方面,如果Foo
和Bar
根本不相关,而你需要这个只是为了智能,我会保留你已经拥有的,然后在...foo as any
里面添加bar
。
推荐阅读
- android - 如何在颤振的小部件中加载(显示)大图像的一部分?
- assembly - x86 binarySearch 实现中的分段错误
- r - RAM 内存使用和管理:R 与 Power BI。为什么 Power Bi 在同一台计算机上处理大型数据集似乎比 R 更好?
- typescript - VSCode 扩展在调试模式下工作正常,但在发布时无法正常工作
- react-native - latlng 不能为空,需要一个位置。反应原生
- condor - HTCondor:在提交文件中,如何评估变量的值以便将其写入输出文件名?
- mysql - 如何填充表单:使用 onclick 图像的数据库记录
- python - 如何搜索音频文件中的内容?
- javascript - Javascript,IF 一键执行两项操作
- java - NumberFormatException - 尝试/捕获解析值