【发布时间】:2021-03-12 23:31:35
【问题描述】:
我正在尝试创建一个通用函数describeToCreate,它根据type 将输入的对象转换为不同的对象。提供的泛型类型T 确定data 的类型和返回对象的类型。提供type 是因为如果没有它,确定data 的类型并非易事。
我已经包含了我正在内联的 Typescript 错误。
功能:
export function dataToCreate<T extends RESOURCE_TYPE>(
type: T,
data: IDataResources[T]
): ICreateResources[T] {
if (type === RESOURCE_TYPE.PHONE) {
// Type Error
// Type 'IPhoneCreate' is not assignable to type 'ICreateResources[T]'.
// Type 'IPhoneCreate' is not assignable to type 'IPhoneCreate & IClockCreate'.
// Argument of type 'IDataResources[T]' is not assignable to parameter of type 'IPhoneData'.
// Type 'IClockData | IPhoneData' is not assignable to type 'IPhoneData'.
return phoneDataToCreate(data);
} else if (type === RESOURCE_TYPE.CLOCK) {
// Type Error
// Type 'IClockCreate' is not assignable to type 'ICreateResources[T]'.
// Type 'IClockCreate' is not assignable to type 'IPhoneCreate & IClockCreate'.
// Argument of type 'IDataResources[T]' is not assignable to parameter of type 'IClockData'.
// Type 'IClockData | IPhoneData' is not assignable to type 'IClockData'.
return clockDataToCreate(data);
}
}
export const phoneDataToCreate = (data: IPhoneData): IPhoneCreate => {
return {
name: data.name,
clockName: data.clockName,
spec: somePhoneTransformationFunction(data),
};
};
export const clockDataToCreate = (data: IClockData): IClockCreate => {
return {
name: data.name,
unit: data.unit,
spec: someClockTransformationFunction(data),
};
};
调用如下:
const create = dataToCreate<RESOURCE_TYPE.CLOCK>(RESOURCE_TYPE.CLOCK, {
name: 'name',
unit: 1000,
spec: { },
})
模型:
enum RESOURCE_TYPE {
PHONE = 'phone',
CLOCK = 'clock',
}
interface IClockData {
name: string;
unit: number;
spec: PhoneDataSpec; // object
}
interface IPhoneData {
name: string;
clockName: string;
spec: PhoneDataSpec; // object
}
interface IClockCreate {
name: string;
unit: number;
spec: PhoneCreateSpec; // object
}
interface IPhoneCreate {
name: string;
clockName: string;
spec: PhoneCreateSpec; // object
}
interface IDataResources {
[RESOURCE_TYPE.PHONE]: IPhoneData;
[RESOURCE_TYPE.CLOCK]: IClockData;
}
interface ICreateResources {
[RESOURCE_TYPE.PHONE]: IPhoneCreate;
[RESOURCE_TYPE.CLOCK]: IClockCreate;
}
当调用dataToCreate 时,它正确地推断出对象是IClockData 而create 是IClockCreate。
【问题讨论】:
标签: typescript typescript-generics