Skip to content

Instantly share code, notes, and snippets.

@k-yle
Last active April 8, 2020 00:29
Show Gist options
  • Save k-yle/e2c74236ecf1a72874c19b28f39e4d11 to your computer and use it in GitHub Desktop.
Save k-yle/e2c74236ecf1a72874c19b28f39e4d11 to your computer and use it in GitHub Desktop.
πŸ’™ returns a different type depending on the value of a function's argument
type Users = any;
type Timetables = any;
type AllTheTypes =
| { name: 'users'; type: Users }
| { name: 'timetables'; type: Timetables }
type GetType<A, T> = A extends { name: T } ? A : never
class MyClass {
public async get<T extends AllTheTypes['name']>(name: T): Promise<GetType<AllTheTypes, T>['type']> {
return /* something based on `name` */
}
public async set<T extends AllTheTypes['name']>(name: T, id: string, data: GetType<AllTheTypes, T>['type']): Promise<void> {
/* do stuff with `name` and `data` */
}
};
const oof = new MyClass();
oof.get('users').then((data) => {
// data is is typeof `Users`
});
oof.get('timetable').then((data) => {
// data is is typeof `Timetables`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment