有两个类:
class STRING_TYPE {
name():string{
return "one";
}
}
class NUMBER_TYPE {
name():number{
return 1;
}
}
我想写一个泛型函数:
- 创建一个给定类的对象
- 调用name()方法,并返回其值;在javascript中,代码如下:
function foo(classType) {
const obj = new classType();
return obj.name();
}
如何用打字稿写?
// it doesn't work.
function foo<T>(typ: T): ReturnType<T.name>{
const obj = new T();
return obj.name();
}
您需要为classType
参数设置约束:
class STRING_TYPE {
value(): string {
return "one";
}
}
class NUMBER_TYPE {
name(): number {
return 1;
}
}
type AnyClass<Return> = new (...args: any[]) => Return
const foo = <Klass extends AnyClass<{ name: () => number }>>(classType: Klass) =>
new classType().name();
const result = foo(NUMBER_TYPE)
游乐场
foo
期望一个具有name
方法的类构造函数。TS能够推断返回类型。
class STRING_TYPE {
name(): string {
return "one";
}
}
class NUMBER_TYPE {
name(): number {
return 1;
}
}
type AnyClass<R> = new (...args: any[]) => R
const foo = <
Return extends { name: () => any },
Klass extends AnyClass<Return>,
>(classType: Klass): ReturnType<InstanceType<Klass>['name']> =>
new classType().name()
foo(NUMBER_TYPE) // number
foo(STRING_TYPE) // string
你可以这样做:
class STRING_TYPE {
value(): string {
return 'one';
}
}
class NUMBER_TYPE {
name(): number {
return 1;
}
}
function foo(classType: typeof STRING_TYPE): string; // ReturnType<STRING_TYPE['value']>
function foo(classType: typeof NUMBER_TYPE): number; // ReturnType<NUMBER_TYPE['name']>
function foo(classType: typeof STRING_TYPE | typeof NUMBER_TYPE) {
const obj = new classType();
return obj instanceof STRING_TYPE ? obj.value() : obj.name();
}
const bar = foo(STRING_TYPE);
const baz = foo(NUMBER_TYPE);
console.log(bar, baz);
游乐场
假设您在这里提问时犯了错字,并且您的两个类都有name
方法,您可以这样做:
class STRING_TYPE {
name(): string {
return 'one';
}
}
class NUMBER_TYPE {
name(): number {
return 1;
}
}
type ClassType =
| typeof STRING_TYPE
| typeof NUMBER_TYPE;
function foo<T extends ClassType>(classType: T) {
const obj = new classType();
return obj.name() as ReturnType<InstanceType<T>['name']>;
}
const bar = foo(STRING_TYPE);
const baz = foo(NUMBER_TYPE);
console.log(bar, baz);
游乐场
引用:
- https://stackoverflow.com/q/12802317 comment31618674_12871488
- https://stackoverflow.com/a/48808100
- https://stackoverflow.com/a/53289298