I'm experiencing inconsistent behavior when I specify the return type of a function inline compared to defining it in a separate type definition.
For instance:
interface Foo {
bar: string;
}
type Fooer = () => Foo;
const foo1: Fooer = () => { // It anticipates `.bar` to be a string
return {
bar: 123,
};
}
// Return type defined in a separate type definition
const foo2: Fooer = () => {
return {
foo: 123, // No complaints about extra properties
bar: "zzz",
};
}
// Inline return type
const foo3: Fooer = (): Foo => {
return {
foo: 123, // Now it does...
bar: "zzz",
};
}
Test it on the TypeScript Playground
I would assume that both foo2
and foo3
would behave the same way (I personally expect both to produce the same error, or to be consistent at least).
What am I overlooking here? What is the distinction between these two approaches?