当我宣布一个泛型类A
中a.js
,并出口it.Then,我不知道如何声明类的变量A
中b.js
。
代码如下a.js
:
export let A = function<K extends { value: number }>(DEFAULT_NUMBER){
return class A<T> {
test(obj: T, num: number): K {
return obj.diff(DEFAULT_NUMBER, num);
};
};
}(
// DEFAULT_NUMBER
1000
);
b.js
import { A } from "a.js";
class B {
diff(): { value: number } {
// ...
}
};
let a: InstanceType<typeof A<B>> = new A();
a.test(new B(), 50);
下面的简单代码:
let A = class<T> {};
class B {};
let a: InstanceType<typeof A<B>>; // throw a syntax error
// or
let a: InstanceType<(typeof A)<B>>; // throw a syntax error
// or
let a: InstanceType<typeof (A<B>)>; // throw a syntax error
// or
let a: (InstanceType<typeof A>)<B>; // throw a syntax error
// or
let a: InstanceType<typeof A>; // correct, but the type of a is `A<unknown>`
我应该如何声明变量a
?
我在两天内一直在考虑这个问题,最后,我找到了答案,代码如下:
type ReplaceItemTypeOf<Target extends any[], NewType, OldType = unknown> = {
// for each item of the array
[Key in keyof Target]: (
// if the type is matched, return NewTypeNewType, otherwise return the origin type of the item value
OldType extends Target[Key] ? NewType : Target[Key]
);
};
type NonAnyType<T> = (T & 1 extends 1 ? 1 : 0) extends 1 ? T : never;
type InstanceTypeOfGenericRef<GenericRef extends new(...args: any) => any, Type> = {
// for each property
[Key in keyof InstanceType<GenericRef>]: (
// if the type is matched unknown type or empty object type
{} extends (
// if property is a method
InstanceType<GenericRef>[Key] extends (...args: any) => infer Result ?
// if type of Result is any return never, otherwise return the origin type of Result
NonAnyType<Result> :
// if type of the property value is any return never, otherwise return the origin type of the property value
NonAnyType<InstanceType<GenericRef>[Key]>
) ?
(
// if property is a method, and type has matched
InstanceType<GenericRef>[Key] extends (...args: infer Args) => infer Result ?
// return a new method interface which has replaced argument types
(...args: ReplaceItemTypeOf<Args, Type>) => Type :
// if not a method, return Type
Type
) :
(
// if property is a method and type has not matched
InstanceType<GenericRef>[Key] extends (...args: infer Args) => infer Result ?
// return a new method interface which has replaced argument types
(...args: ReplaceItemTypeOf<Args, Type>) => Result :
// return origin type of the property value
InstanceType<GenericRef>[Key]
)
);
};
let A = class A<T> {
set(value: T): T {
return value;
}
}
let a: InstanceTypeOfGenericRef<typeof A, string>;
a.set("123");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句