I have a function which accepts a single object parameter as follows. (Note, this is a contrived example but it demonstrates the problem.)
type FuncParams = { sayYes: boolean; }
type FuncType = (params: FuncParams) => string;
const maybeSayYes: FuncType = ({ sayYes }) => sayYes ? 'Yes' : 'No';
maybeSayYes({ sayYes: true }); // Returns 'Yes'
maybeSayYes({ sayYes: false }); // Returns 'No'
I want to make the sayYes property optional, so I updated the types as follows and added a default to the function declaration:
type FuncParams = { sayYes?: boolean; }
type FuncType = (params: FuncParams) => string;
const maybeSayYes: FuncType = ({ sayYes = true }) => sayYes ? 'Yes' : 'No';
maybeSayYes({ sayYes: true }); // Returns 'Yes'
maybeSayYes({ sayYes: false }); // Returns 'No'
maybeSayYes({}); // Returns 'Yes'
However, I noticed that I can assign any default value to sayYes and TypeScript doesn't flag up the incorrect type. For example:
const maybeSayYes: FuncType = ({ sayYes = 'notABoolean' }) => sayYes ? 'Yes' : 'No';
I expected TypeScript to infer the boolean type from FuncType and stop me assigning a string, but it doesn't.
I can get the error to show if I explicitly type the parameter as follows:
const maybeSayYes: FuncType = ({ sayYes = 'notABoolean' }: FuncParams) => sayYes ? 'Yes' : 'No';
However, I assumed TypeScript would infer this type from FuncType. I'm sure it's my understanding of TypeScript that's at fault, but I'd like to know:
- Why TypeScript doesn't tell me that
'notABoolean'isn't aboolean. - How I can constrain the default value type without having to duplicate the
FuncParamstyping.
booleangets messed up (as it's represented astrue | false).