如何从已有TypeScript类型中递归提取所有函数(含嵌套函数)
提取TypeScript类型中所有嵌套函数的解决方案
我需要实现一个TypeScript类型工具,能从已有类型中提取所有函数(包括嵌套对象里的函数)。目前我只能提取顶层的函数,代码如下:
interface Foo { doSomethingFoo(): void bar: Bar anotherProperty: boolean arrayProperty: Bar[], arrayPrimitive: string[], } interface Bar { doSomethingBar(): void anotherProperty: string } type PickFunctions<T> = { [P in keyof T as T[P] extends Function ? P : never]: T[P] } type fooFunctions = PickFunctions<Foo> /* type fooFunctions = { doSomethingFoo: () => void; } */
但我需要的是,给类型Foo时,得到包含所有函数、且内部对象仅保留函数的结构;如果遇到对象数组,要转换成单个对象类型(只关注函数,不管数组实例数据),期望结果如下:
declare type OnlyFunctions<T> type fooAndNestedFunctions = OnlyFunctions<Foo> /* Should be: type fooAndNestedFunctions = { doSomethingFoo: () => void; bar: { doSomethingBar: () => void; }; arrayProperty: { doSomethingBar: () => void; }; } */
在@jcalz的建议下,我得到了如下解决方案:
type RecursivePickFunctions<T> = { [K in keyof T as T[K] extends any[] ? Unarray<T[K]> extends object ? K : never : T[K] extends object ? K : never ]: T[K] extends Function ? T[K] : T[K] extends object[] ? RecursivePickFunctions<Unarray<T[K]>> : RecursivePickFunctions<T[K]> } type Unarray<T> = T extends Array<infer U> ? U : T type fooFunctions = RecursivePickFunctions<Foo> /* type FooFunctions = { doSomethingFoo: () => void; bar: RecursivePickFunctions<Bar>; arrayProperty: RecursivePickFunctions<Bar>; } */
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

