【发布时间】:2020-12-29 11:10:43
【问题描述】:
我想创建一个类型正确的函数,它接收带有服务名称的参数并返回该服务的实例。如果不强制转换实例,我将无法获得结果。
用一个简化的例子更好地解释:
class ECR {
public image(): void {}
}
class ECS {
public cluster(): void {}
}
const aws = {
ECR,
ECS
};
type Aws = {
ECR: ECR
ECS: ECS
}
function createService<T extends 'ECR' | 'ECS'>( serviceName: T, aws: typeof AWS ): Aws[T] {
const Constr = aws[ serviceName ];
const f: Aws[T] = new Constr(); // here I receive the error if do not cast it 'as Aws[T]'
return f;
}
错误:
Type 'ECR | ECS' is not assignable to type 'Aws[T]'.
Type 'ECR' is not assignable to type 'Aws[T]'.
Type 'ECR' is not assignable to type 'ECR & ECS'.
Property 'cluster' is missing in type 'ECR' but required in type 'ECS'.
知道如何在不需要强制转换的情况下正确键入此函数吗?
【问题讨论】:
标签: typescript types casting typescript-generics