Typescript 如何将接口转换为特定接口的数组
我有一个带有Typescript 如何将接口转换为特定接口的数组,typescript,Typescript,我有一个带有属性的对象。每个属性都有属性列表,其值类型取决于键值。我正在尝试创建泛型类型,以便将属性类型的接口转换为我的结构 下面是我当前代码的示例。我无法为属性设置类型 interface IAttribute<Key, Value> { key: Key; value: Value; approved?: boolean; published?: boolean; fromPrototype?: boolean; } interface IObject<
属性的对象。每个属性都有属性列表,其值类型取决于键值。我正在尝试创建泛型类型,以便将属性类型的接口转换为我的结构
下面是我当前代码的示例。我无法为属性设置类型
interface IAttribute<Key, Value> {
key: Key;
value: Value;
approved?: boolean;
published?: boolean;
fromPrototype?: boolean;
}
interface IObject<T> {
id: string;
attributes?: Array<IAttribute<K, T[K]>>; // K extends keyof T. How can I fix it?
}
interface ICustomAttributes {
attr1: boolean;
attr2: number;
}
type ICustom = IObject<ICustomAttributes>;
const o: ICustom = {
id: "1",
attributes: [
{
key: "attr1",
value: true,
},
{
key: "attr2",
value: 123,
},
],
}
接口属性{
键:键;
价值:价值;
批准?:布尔值;
已发布?:布尔值;
fromPrototype?:布尔;
}
接口对象{
id:字符串;
属性?:数组;//K扩展了keyof T。如何修复它?
}
接口ICustomAttribute{
属性1:布尔型;
属性2:数量;
}
类型ICustom=IOObject;
常数o:ICustom={
id:“1”,
属性:[
{
键:“attr1”,
价值观:正确,
},
{
键:“attr2”,
价值:123,
},
],
}
最终结果必须是这样的
type ICustomAttributes = IAttribute<"attr1", boolean> | IAttribute<"attr2", number>;
interface ICustom {
id: string;
attributes?: ICustomAttributes[]
}
类型ICustomAttributes=IAttribute | IAttribute;
接口ICustom{
id:字符串;
属性?:ICustomAttributes[]
}
您可以使用映射类型将类型的属性转换为IAttribute的并集:
interface IAttribute<Key, Value> {
key: Key;
value: Value;
approved?: boolean;
published?: boolean;
fromPrototype?: boolean;
}
interface IObject<T> {
id: string;
attributes?: Array<{ [P in keyof T]: IAttribute<P, T[P]> }[keyof T]>; // K extends keyof T. How can I fix it?
}
interface ICustomAttributes {
attr1: boolean;
attr2: number;
}
type ICustom = IObject<ICustomAttributes>;
const o: ICustom = {
id: "1",
attributes: [
{
key: "attr1",
value: true,
},
{
key: "attr2",
value: 123,
},
],
}
接口属性{
键:键;
价值:价值;
批准?:布尔值;
已发布?:布尔值;
fromPrototype?:布尔;
}
接口对象{
id:字符串;
属性?:数组;//K扩展了keyof T。如何修复它?
}
接口ICustomAttribute{
属性1:布尔型;
属性2:数量;
}
类型ICustom=IOObject;
常数o:ICustom={
id:“1”,
属性:[
{
键:“attr1”,
价值观:正确,
},
{
键:“attr2”,
价值:123,
},
],
}
然而,这并不能确保每个成员至少出现一次,并且没有重复。根据您的用例,这可能是问题,也可能不是问题。如果需要确保在使用对象而不是数组时,每个成员都正好存在(使用元组可以实现类似的效果,但将对象类型转换为所有可能元组的并集需要使用递归类型别名,这是不推荐的)
接口对象{
id:字符串;
属性?:{[P in keyof T]:IAttribute}
}
接口ICustomAttribute{
属性1:布尔型;
属性2:数量;
}
类型ICustom=IOObject;
常数o:ICustom={
id:“1”,
属性:{
“属性1”:{
键:“attr1”,
价值观:正确,
},
“属性2”:{
键:“attr2”,
价值:123,
},
}
}
一个属性是string/boolean,另一个是string/number?key
是属性名,value
是属性值<代码>值
类型取决于键
。它可以是任意的。您是否打算允许多次将attr1
添加到对象中?
interface IObject<T> {
id: string;
attributes?: { [P in keyof T]: IAttribute<P, T[P]> }
}
interface ICustomAttributes {
attr1: boolean;
attr2: number;
}
type ICustom = IObject<ICustomAttributes>;
const o: ICustom = {
id: "1",
attributes: {
"attr1": {
key: "attr1",
value: true,
},
"attr2": {
key: "attr2",
value: 123,
},
}
}