When giving a default value to a property of an object used as an argument, TypeScript widens the type if the default value does not match the type from the function definition.
What’s the best way to avoid that ? I want typescript to complain if the default value is not red or green in the following example:
// The real FC generic type does more than that (demo purpose)
type FC<T> = (props: T) => void
type Props = { color?: 'red' | 'green' }
// no type error because TypeScript widens the type
const f: FC<Props> = ({ color = 'not a valid color' }) => {
// and color is a string here
}
The only option I see:
const f: FC<Props> = ({ color = 'not a valid color' }: Props) => {}
This is not an option (not the same behaviour when there are multiple properties, plus color can be undefined now):
const g: FC<Props> = ({ color } = { color: 'ts will not be happy' }) => {}