Skip to content

Instantly share code, notes, and snippets.

@InfiniteXyy
Created November 25, 2020 15:14
Show Gist options
  • Save InfiniteXyy/05fe5dc9d8cc52ba544f2bbd97643b22 to your computer and use it in GitHub Desktop.
Save InfiniteXyy/05fe5dc9d8cc52ba544f2bbd97643b22 to your computer and use it in GitHub Desktop.
// forked from https://github.com/ahejlsberg/tsconf2020-demos/blob/master/template/main.ts
type SubKeys<T, K extends string> = K extends keyof T ? `${K}.${PathKeys<T[K]>}` : never
type PathKeys<T> = object extends T
? string
: T extends readonly any[]
? Extract<keyof T, `${number}`> | SubKeys<T, Extract<keyof T, `${number}`>>
: T extends object
? Extract<keyof T, string> | SubKeys<T, Extract<keyof T, string>>
: never
type PropType<T, Path extends string> = Path extends keyof T
? T[Path]
: Path extends `${infer K}.${infer R}`
? K extends keyof T
? PropType<T[K], R>
: unknown
: unknown
// i18n example
declare function useI18n<T>(i18n: T): <P extends PathKeys<T>>(path: P) => PropType<T, P>
interface HomeI18n {
setting: string
menu: {
close: string
expand: string
}
}
const t = useI18n({} as HomeI18n)
t("menu.close")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment