const foo : {[key:string]:string} = {'hello': 'world', 'hi': 'there'};
const bar : number = 42
const foobar = {...foo, bar}
console.log(foobar)
// { hello: 'world', hi: 'there', bar: 42 }
The type of foobar resolves to {bar: number}. Why is this? I would expect the type of foobar to be {[key:string]: string|number} or {[key:string]: string} & {bar: number}
EDIT: I'm particularly confused on why in some cases the types are determined correctly:
const foo : {a: number} = {a: 1}
const bar : string = "bar"
const foobar = {...foo, bar}
console.log(foobar)
// foobar is type {bar: string, a: number}
Why does this case work, and the first case doesn't?
interface Foo {a: number; b: string}suggests something with typeFoohas anaandbproperty. However{a: 1, b: "two", c: false}is assignable toFoo. The compiler will not allow you to accesscbut it cannot assume it's not there. When getting all keys of an object there is no type safety in the general case. That leads to some behaviours that seem odd looking at types alone but are better suited for the real world code.