Can someone explain why I am getting a compiler warning from Typescript when attempting to create a new object based on an existing object of the same type?
In the snippet below, spreading the key2
value results in the error message
Type 'string | undefined' is not assignable to type 'string'.
. Even though key2
is optional, I am spreading the value from object1
which we know contains a key2
entry.
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 error:
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)
I am seeking to understand this behavior and the best approach to address such situations.
Appreciate your insights