I am working on defining a function type that enforces the return type (Object) to have the exact object properties specified in the return type definition.
Despite my efforts, the compiler is not enforcing strict adherence to the returned object properties and allows additional properties that are not defined in the return type.
interface Obj {
foo: string;
}
type Func = () => Obj;
const fn: Func = () => {
return {
foo: 'bar',
blah: '', // the compiler does not raise an error
};
};
However, if I explicitly specify the return type as Obj
in the fn
function, the compiler correctly flags any extra properties.
interface Obj {
foo: string;
}
const fn = (): Obj => {
return {
foo: 'bar',
blah: '', // the compiler raises an error
};
};
Could someone provide insight into why TypeScript handles these scenarios differently? Is there a way to maintain return type strictness when using a function type?