我有以下typescript定义:
interface myType {
A: {
instance: someInstance,
...
},
B: {
instance: someOtherInstance,
...
}
}我想创建一个类型,它接受myType接口的所有属性,并生成一个对象,该对象接受来自该接口的实例类型。大致是这样的:
type myBasicType<TType> = '...';
const a: myBasicType<myType> = {
A: '...', // an instance of someInstance here
B: '...', // an instance of someOtherInstance here
}基本上,我需要的是一个功能,它生成一个基于接口的类型,其中原始接口的属性保持不变,但它们的类型根据原始接口的特定属性更改为新类型。
发布于 2021-11-04 08:11:05
您可以使用mapped types
class someInstance {
tag: 'someInstance' = 'someInstance'
}
class someOtherInstance {
tag: 'someOtherInstance' = 'someOtherInstance'
}
interface myType {
A: {
instance: someInstance,
},
B: {
instance: someOtherInstance,
}
}
type Mapper<T> = {
[Prop in keyof T]: T[Prop] extends { instance: unknown } ? T[Prop]['instance'] : never
}
// type Result = {
// A: someInstance;
// B: someOtherInstance;
// }
type Result = Mapper<myType>https://stackoverflow.com/questions/69835956
复制相似问题