【发布时间】:2022-01-23 16:50:33
【问题描述】:
我有如下界面:
export interface IFormField {
/** Field name */
name: string;
/** Label to appear on form */
label?: string; // this is optional, since hidden fields do not have label
/** Field type */
type: 'accordion' | 'address' | 'camera' | 'category_box' | 'category_list';
}
我想扩展type 的有效值,通过像这样的对象来选择它们:
const arr = {
'new_type1': 1,
'new_type2': 2,
'new_type3': 3,
};
如何将new_type1、new_type2 和new_type3 添加到type 字段的有效名称列表中?
因此,我想要:
type: 'accordion' | 'address' | 'camera' | 'category_box' | 'category_list' | `new_type1` | `new_type2` | `new_type3`;
另一个完整(不工作)的例子:
const arr: any = {
'new_type1': 1,
'new_type2': 2,
'new_type3': 3,
};
export interface IFormField {
/** Field name */
name: string;
/** Label to appear on form */
label?: string; // this is optional, since hidden fields do not have label
/** Field type */
type: keyof typeof arr;
}
const f: IFormField = {
name: 'ciao',
type: "new_type1"
};
// adding a new key to `arr` at runtime
arr.type4 = 4;
const g: IFormField = {
name: 'cioa',
type: 'type4' // <- valid for IFormField.type ?
}
有可能吗?
谢谢
【问题讨论】:
标签: typescript