Skip to content

Instantly share code, notes, and snippets.

@elado
Created November 2, 2021 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elado/420afd3f3a57483511e84a1111dc1bf2 to your computer and use it in GitHub Desktop.
Save elado/420afd3f3a57483511e84a1111dc1bf2 to your computer and use it in GitHub Desktop.
TypeScript type maps
export enum EnumType {
Foo = 'Foo',
Bar = 'Bar',
}
export interface MapEnumTypeToDataType {
[EnumType.Foo]: { x: string };
[EnumType.Bar]: { y: string };
}
function fn<TEnumType extends EnumType>(name: TEnumType, data: MapEnumTypeToDataType[TEnumType]) {
console.log(name, data);
}
export interface MapStringTypeToDataType {
"foo": { x: string };
"bar": { y: string };
}
function fn2<TStringType extends keyof MapStringTypeToDataType>(name: TStringType, data: MapStringTypeToDataType[TStringType]) {
console.log(name, data);
}
fn(EnumType.Foo, { x: 'foo' });
fn(EnumType.Bar, { y: 'bar' });
fn2("foo", { x: 'foo' });
fn2("bar", { y: 'bar' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment