'Why don't I get a type error when combining these apparently-incompatible objects with the spread operator?
Here's my minimal reproduction:
const br: Record<string, number> = {"b": 0};
const ar: {a: string} = {a: ""};
const brar: Record<string, string> = {...ar, ...br};
console.log(brar);
It seems to me like brar
should not be allowed, since it claims to have only values of type string
, but contains a number
at key "b"
. Yet the typescript playground seems to accept it. What's going on?
Some changes that seem to cause a type error to arise:
- using
Record<"b", number>
forbr
, or using no type signature at all, - using
Record<string, string>
forar
(thoughRecord<"a", string>
is fine).
edit: it turns out ar
can be inlined, leading to an arguably even more minimal reproduction:
const br: Record<string, number> = {b: 0};
const abr: Record<string, string> = {a: "", ...br};
console.log(abr);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|