当泛型属于某种类型时是否可以创建别名?
Is it possible to create an alias for when a generic is of a certain type?
我想要一个采用泛型的类型,它扩展了一个 函数对象和 'nested' 函数 和 "returns" 一个 对象,其中每个函数都有一个修改后的函数签名.
所以这个
{ foo: (a) => (b) => ({}), nested: { bar: (a) => (b) => ({}) } }
变成这样
{ foo: (a) => ({}), nested: { bar: (a) => ({}) } }
我试过这样输入:
type Convertor<
T extends { [key: string]: NestedMap<Function> | Function }
> = { [P in keyof T]: Converting<T[P]> }
这不起作用,因为 Converting<T[P]>
应该只在它是函数时发生。 IE。 foo
和 nested.bar
但不是 nested
,因为那是一个对象。
如何正确输入?
在 conditional types 落地之前您可以使用
来自 https://github.com/Microsoft/TypeScript/issues/12424#issuecomment-356685955
的疯狂解决方案
type False = '0';
type True = '1';
type If<C extends True | False, Then, Else> = { '0': Else, '1': Then }[C];
type Diff<T extends string, U extends string> = (
{ [P in T]: P } & { [P in U]: never } & { [x: string]: never }
)[T];
type X<T> = Diff<keyof T, keyof Object>
type Is<T, U> = (Record<X<T & U>, False> & Record<any, True>)[Diff<X<T>, X<U>>]
type DeepFun<T> = {
[P in keyof T]: If<Is<Function & T[P], Function>, ()=>{}, DeepFun<T[P]>>
}
type MyType = { foo: (a:any) => (b:any) => ({}), nested: { bar: (a:any) => (b:any) => ({}) } }
type NewType = DeepFun<MyType>;
var d:NewType; // type is {foo: ()=>{}, nested: {bar: ()=>{}}}
我想要一个采用泛型的类型,它扩展了一个 函数对象和 'nested' 函数 和 "returns" 一个 对象,其中每个函数都有一个修改后的函数签名.
所以这个
{ foo: (a) => (b) => ({}), nested: { bar: (a) => (b) => ({}) } }
变成这样
{ foo: (a) => ({}), nested: { bar: (a) => ({}) } }
我试过这样输入:
type Convertor<
T extends { [key: string]: NestedMap<Function> | Function }
> = { [P in keyof T]: Converting<T[P]> }
这不起作用,因为 Converting<T[P]>
应该只在它是函数时发生。 IE。 foo
和 nested.bar
但不是 nested
,因为那是一个对象。
如何正确输入?
在 conditional types 落地之前您可以使用 来自 https://github.com/Microsoft/TypeScript/issues/12424#issuecomment-356685955
的疯狂解决方案type False = '0';
type True = '1';
type If<C extends True | False, Then, Else> = { '0': Else, '1': Then }[C];
type Diff<T extends string, U extends string> = (
{ [P in T]: P } & { [P in U]: never } & { [x: string]: never }
)[T];
type X<T> = Diff<keyof T, keyof Object>
type Is<T, U> = (Record<X<T & U>, False> & Record<any, True>)[Diff<X<T>, X<U>>]
type DeepFun<T> = {
[P in keyof T]: If<Is<Function & T[P], Function>, ()=>{}, DeepFun<T[P]>>
}
type MyType = { foo: (a:any) => (b:any) => ({}), nested: { bar: (a:any) => (b:any) => ({}) } }
type NewType = DeepFun<MyType>;
var d:NewType; // type is {foo: ()=>{}, nested: {bar: ()=>{}}}