[Typescript] Type incompatible function argument as never
For the following code:
const objOfFunctions = {
string: (input: string) => input.toUpperCase(),
number: (input: number) => input.toFixed(2),
boolean: (input: boolean) => (input ? "true" : "false"),
};
const format = (input: string | number | boolean) => {
const inputType = typeof input as "string" | "number" | "boolean";
const formatter = objOfFunctions[inputType];
return formatter(input); // Error: Argument of type 'string | number | boolean' is not assignable to parameter of type 'never'.
// Type 'string' is not assignable to type 'never'.
};
This is due to input
is typed as intersection of string & number & boolean
which results as never
So you have to do:
const format = (input: string | number | boolean) => {
const inputType = typeof input as "string" | "number" | "boolean";
const formatter = objOfFunctions[inputType];
return formatter(input as never);
};