Can you help me understand why TypeScript behaves differently when defining entities using types directly versus returning them from functions?
type Entity =
| { text: string; color?: never; icon?: never }
| { text: string; color: string; icon?: string }
const entities: Entity[] = [
// ok
{ text: 'foo' },
{ text: 'foo', color: 'red' },
{ text: 'foo', color: 'red', icon: 'apple' },
// error ~ 'color' is missing
{ text: 'foo', icon: 'apple' },
]
type EntityFn =
| (() => { text: string; color?: never; icon?: never })
| (() => { text: string; color: string; icon?: string })
const entityFns: EntityFn[] = [
// ok
() => ({ text: 'foo' }),
() => ({ text: 'foo', color: 'red' }),
() => ({ text: 'foo', color: 'red', icon: 'apple' }),
// Unexpectedly no error thrown here
() => ({ text: 'foo', icon: 'apple' }),
]
Appending an unassignable function to entityFns
, makes the compiler start complaining about a different entity. Can you explain this behavior?
Playground link for reference: playground link