Created
May 14, 2021 13:53
-
-
Save shirakaba/776cb73bebf7d5d4bca31acc0cbfe139 to your computer and use it in GitHub Desktop.
TypeScript guard function for type-checking records by index signatures
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 Check<T> = { | |
| [K in keyof T]: K extends `dull.${string}` | |
| ? T[K] extends string | |
| ? T[K] | |
| : never | |
| : K extends `rich.${string}` | |
| ? T[K] | |
| : never | |
| } | |
| function isRichAndDull<T extends Record<string, any>>(value: Check<T>): Check<T> { | |
| return value | |
| } | |
| const config = isRichAndDull({ | |
| "dull.foo": "hello", | |
| "rich.foo": new Date(), | |
| }) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What I'm ultimately aiming for, though, is something like this:
... However, it fails with:
An index signature parameter type must be either 'string' or 'number'.in TypeScript 4.3.