[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 inputis typed as intersection of string & number & booleanwhich 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);
};

 

posted @ 2024-08-07 17:53  Zhentiw  阅读(6)  评论(0编辑  收藏  举报