Last active
May 7, 2019 21:15
-
-
Save Grohden/1402a82af3c172c008e82baee9b95946 to your computer and use it in GitHub Desktop.
My try on dependent types + conditional types using typescript to validate optional args based on a key
This file contains 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 Routes = { | |
a: { | |
string: string | |
} | |
b: undefined | |
} | |
type NullableKeys<T, K extends keyof T> = T[K] extends null | undefined | |
? K | |
: never; | |
type NonNullableKeys<T, K extends keyof T> = T[K] extends null | undefined | |
? never | |
: K; | |
declare function teste<R extends keyof Routes>( | |
a: NullableKeys<Routes, R> | |
) | |
declare function teste<R extends keyof Routes>( | |
a: NonNullableKeys<Routes, R>, | |
b: Routes[R] | |
) | |
teste('a') // error | |
teste('a', { string: 'test'}) // ok | |
teste('b', { string: 'test'}) // error | |
teste('b') // ok |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment