I have a problem with return type of the function. In the example, if I explicitly define return type Foo, it shows error as expected. If I add type to function, an error is not shown.
It seems that in foo2 should be at least object extended from Foo, if I remove "a" from foo2, it says this:
Type '() => { b: string; }' is not assignable to type 'FooFn'. Type '{ b: string; }' has no properties in common with type 'Foo'.
interface Foo {
a?: string
}
type FooFn = () => Foo
const foo = (): Foo => {
return {
a: 'a',
b: 'b', // OK
}
}
const foo2: FooFn = () => {
return {
a: 'a',
b: 'b', // Why is not error also here???
}
}
The only option, that I think of is making it something like that:
interface Foo {
a?: string
}
// I cant figure it out, how to write it ...
type FooFn = () => Record<string, key is from keyof Foo ? string : never>
Is it possible to make type, which only accepts keyof Foo and the rest is never?
Playground: