TypeScript: how do I type a function that returns different types based on an argument?

poze 3 months ago298 gadeen

1

I have:

function parse(value: string, as: 'number' | 'boolean') {
  return as === 'number' ? Number(value) : value === 'true';
}
const n = parse('42', 'number'); // type is number | boolean

I want n to be typed number when I pass 'number'. Is that possible?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 3 months ago

2 Repons

7
✓
✓ Repons yo aksepte

Yes, with function overloads:

function parse(value: string, as: 'number'): number;
function parse(value: string, as: 'boolean'): boolean;
function parse(value: string, as: 'number' | 'boolean'): number | boolean {
  return as === 'number' ? Number(value) : value === 'true';
}

const n = parse('42', 'number');   // number
const b = parse('true', 'boolean'); // boolean

The last signature is the implementation and isn't visible to callers.

Konekte pou di lòt moun si li te mache.

answered 3 months ago
6

A generic lookup-type version scales better when there are many options:

type ParseMap = { number: number; boolean: boolean; date: Date };

function parse<K extends keyof ParseMap>(value: string, as: K): ParseMap[K] {
  const parsers = {
    number: Number,
    boolean: (v: string) => v === 'true',
    date: (v: string) => new Date(v),
  } satisfies { [P in keyof ParseMap]: (v: string) => ParseMap[P] };
  return parsers[as](value) as ParseMap[K];
}

Konekte pou di lòt moun si li te mache.

answered 3 months ago

Sign in and verify your email to post an answer.