Last active
April 8, 2020 00:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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