I'm using the spread operator to create a copy with a changed field like in the following example (run). But the compiler doesn't complain if the type of the field is changed when the object literal is created:
class A{
constructor(readonly a: number, readonly b: string[]){}
copy(): A { // must return an object of type A
return {
...this,
b: 99 // should be of type string[]!
}
}
}
const a: A = new A(1, ["x", "y"])
const a1 = a.copy()
console.log(JSON.stringify(a1))
Output:
[LOG]: "{"a":1,"b":99}"
Creating an explicit interface also doesn't help:
interface IA {
readonly a: number
readonly b: string[]
}
...
copy(): IA { ...
It looks like it had nothing to do with arrays, since the next example compiles as well:
class A{
constructor(readonly a: number, readonly b: number){}
copy(): A {
return {
...this,
b: "my string" // should be of type number!
}
}
}
Why is this possible in TypeScript? Or is it a compiler bug? Is there a way to avoid