I've been observing some peculiar behavior:
In a typical scenario, TypeScript usually raises an error when an object contains too many keys, like this:
type Foo = {
a: string;
}
const a: Foo = {
a: "hello",
b: "foo" // Object literal may only specify known properties, and 'b' does not exist in type 'Foo'.(2322)
};
function returnsFoo() : Foo {
return {
a: 'hello',
b: "world" // Object literal may only specify known properties, and 'b' does not exist in type 'Foo'.(2322)
}
}
However, I noticed that if instead of directly declaring a function, I define a type that includes a function as a property, this error mysteriously disappears:
type ObjectThatHasAFunctionThatReturnsFoo = {
defaultData: () => Foo;
};
const b: ObjectThatHasAFunctionThatReturnsFoo = {
defaultData: ()=> ({
a: "hello",
//@ts-expect-error - but no error.
b: "asa"
})
}
What could be the reason behind this unexpected behavior?