typescript中的keyPath提示
更新时间:2023-02-22 15:57:53标签:web前端typescript
1type DotPrefix<T extends string> = T extends '' ? '' : `.${T}`;23type KeyPaths<T> = (4 T extends object ?5 { [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<KeyPaths<T[K]>> | ''}` }[Exclude<keyof T, symbol>] :6 ''7 ) extends infer D ?8 Extract<D, string> :9 never;1011const obj = {12 a: 1,13 b: {14 c: true,15 d: {16 e: 'string',17 },18 },19};20function getValue(keyPath: KeyPaths<typeof obj>) {2122}23getValue('b.d.e');24getValue('b.d');25getValue('a');