Home > Software design >  Use conditional type as return type doesn't work correctly
Use conditional type as return type doesn't work correctly

Time:05-23

I want to get a string based on the type of the input parameter of a function toTypeString as follows:

function toTypeString<T extends string | number>(x: T): T extends string ? "S" : T extends number ? "N": never {
  if (typeof x === 'string') return 'S';
  if (typeof x === 'number') return 'N';
  throw new Error(`unexpected value: ${x}`);
}

It works, but doesn't compile with the following error:

Type '"S"' is not assignable to type 'T extends string ? "S" : T extends number ? "N" : never'.
Type '"N"' is not assignable to type 'T extends string ? "S" : T extends number ? "N" : never'.

(playground)

How can I fix this error?

CodePudding user response:

I would use function overloading here:

function toTypeString<T extends string | number>(x: T): T extends string ? "S" : T extends number ? "N": never
function toTypeString(x: string | number): "S" | "N" {
  if (typeof x === 'string') return 'S';
  if (typeof x === 'number') return 'N';
  throw new Error(`unexpected value: ${x}`);
}

Playground

  • Related