我有一个属性列表,应该作为不同类型接口的键。如何更好地实现它们?我不允许使用enum中不存在的属性。
export enum SomePropetries {
prop1,
prop2,
prop3
};
export interface PropsInterface {
[SomePropetries.prop1]: number;
[SomePropetries.prop2]: boolean;
[SomePropetries.prop3]: string;
}
// Usage example.
// I have object of properties. Each of property can be updated separatelly.
let props: PropsInterface = {
[SomePropetries.prop1]: null,
[SomePropetries.prop2]: null,
[SomePropetries.prop3]: null
};
const fieldToUpdate: {
field: SomePropetries;
value: number;
} = {
field: SomePropetries.prop1,
value: 123
};
props[fieldToUpdate.field] = fieldToUpdate.value;
首先,您需要使PropsInterface
的所有属性可为空。
export enum SomePropetries {
prop1,
prop2,
prop3
};
interface PropsBase {
[SomePropetries.prop1]: number;
[SomePropetries.prop2]: boolean;
[SomePropetries.prop3]: string;
}
type NullableRecord<T> = {
[Prop in keyof T]: T[Prop] | null
}
type PropsInterface = NullableRecord<PropsBase>
然后,允许使用null
作为属性类型。
let props: PropsInterface = {
[SomePropetries.prop1]: null,
[SomePropetries.prop2]: null,
[SomePropetries.prop3]: null
}
这行不通,
const fieldToUpdate = {
field: SomePropetries.prop1,
value: 123
}
props[fieldToUpdate.field] = fieldToUpdate.value;
,因为fieldToUpdate.field
推断为enum
。我的意思是它期望所有可能的枚举键,而您只对一个SomePropetries.prop1
感兴趣。
因此,为了使它工作,您应该使用as const
断言。
const fieldToUpdate = {
field: SomePropetries.prop1,
value: 123
} as const
props[fieldToUpdate.field] = fieldToUpdate.value;
整个代码:
export enum SomePropetries {
prop1,
prop2,
prop3
};
interface PropsBase {
[SomePropetries.prop1]: number;
[SomePropetries.prop2]: boolean;
[SomePropetries.prop3]: string;
}
type NullableRecord<T> = {
[Prop in keyof T]: T[Prop] | null
}
type PropsInterface = NullableRecord<PropsBase>
// Usage exanple.
// I have object of properties. Each of property can be updated separatelly.
let props: PropsInterface = {
[SomePropetries.prop1]: null,
[SomePropetries.prop2]: null,
[SomePropetries.prop3]: null
};
const fieldToUpdate = {
field: SomePropetries.prop1,
value: 123
} as const
props[fieldToUpdate.field] = fieldToUpdate.value;
游乐场