Skip to content

Instantly share code, notes, and snippets.

@Grohden
Last active May 7, 2019 21:15
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 Grohden/1402a82af3c172c008e82baee9b95946 to your computer and use it in GitHub Desktop.
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
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