Home > OS >  Dispatch different function depending on type of generic
Dispatch different function depending on type of generic

Time:01-18

I want to write a function that lets me dispatch on the type of the generic passed in. I don't care about the runtime value, JUST the compile time type:

const value: any;
const x: DateTime = parseAs<DateTime>(value)
const y: string = parseAs<string>(value)
const z: number = parseAs<number>(value)

The implementation of each parseAs function we can assume is irrelevant (just that it takes a value of any, and returns the type in A

Is this possible? I.e. calling a diff function depending on the generic param passed in. I don't care about the value param passed in, I just want to blindly call a parse function on it

CodePudding user response:

Because type information is erased before the emit step during compilation, it's not possible to affect runtime values using type information.

However, if ergonomics is your goal, then you can use an overloaded function to achieve a strongly-typed result like this:

TS Playground

// I presume this is a type you created, so
// I'll set it to Date for this example:
type DateTime = Date;

type ParseFormat = 'DateTime' | 'string' | 'number';

function parseAs(format: 'DateTime', value: unknown): DateTime;
function parseAs(format: 'string', value: unknown): string;
function parseAs(format: 'number', value: unknown): number;
function parseAs(format: ParseFormat, value: unknown) {
  // Actually implement
  return undefined as any;
}

// Then using is just as ergonomic as supplying a type generic:
declare const value: any;
parseAs('DateTime', value); // DateTime
parseAs('string', value); // string
parseAs('number', value); // number

  •  Tags:  
  • Related