我试图理解为什么我在try 基于同一类型的现有对象创建新对象时,会从Typescript中得到编译器警告.
在下面的代码中,您可以看到散布key2
值会导致错误Type 'string | undefined' is not assignable to type 'string'.
.虽然key2
是可选的,但我将object1
的值分散开来,我们知道它有一个key2
条目.
type Test = {
key1: string;
key2?: {
key3: string;
}
}
const object1:Test = {
key1: "hello",
key2: {
key3: "hi"
}
}
const object2:Test = {
...object1,
key2: { // error here
...object1.key2
}
}
类型错误:
Type '{ key3?: string | undefined; }' is not assignable to type '{ key3: string; }'.
Types of property 'key3' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.(2322)
我只是想了解这里的行为,以及处理这种情况的最佳方式.
谢谢