TypeScript:常量数组作为类型定义



我正在做一个typescript项目,在定义一个合适的类型时有点挣扎。背景:

我在我的项目中得到了以下常量:

export const PROPERTYOPTIONS = [
{ value: "tag", label: "Tag" }, 
{ value: "composition", label: "Composition" },
{ value: "solvent", label: "Solvent" },
{ value: "allergen", label: "Allergen" },
{ value: "category", label: "Category" },
{ value: "other", label: "Other" },
];

现在我想定义一个接口:

interface CreatePropertyModalState {
type: { value: string; label: string };
}

我如何定义类型字段的类型是PROPERTYOPTIONS的成员?

我想避开像

这样的类型定义:
type: { value: "tag" | "composition" | .....

如果您不打算在运行时更改PROPERTYOPTIONS的内容,您可以将其标记为不可变(as const),并使用typeof为其定义类型别名:

export const PROPERTYOPTIONS = [
{ value: 'tag', label: 'Tag' }, 
{ value: 'composition', label: 'Composition' },
{ value: 'solvent', label: 'Solvent' },
{ value: 'allergen', label: 'Allergen' },
{ value: 'category', label: 'Category' },
{ value: 'other', label: 'Other' },
] as const
type PropertyOptions = typeof PROPERTYOPTIONS
type PropertyOption = PropertyOption[number]
interface CreatePropertyModalState {
// if the type should be exactly one of the options
type: PropertyOption,
// if you want to combine an allowed value with an arbitrary label
type: { value: PropertyOption['value'], label: string },
}

您可以使用泛型标识函数来约束数组的类型,然后使用索引访问类型的typeof来提取您想要的类型。

function checkArray<T extends string>(arr: {value: T, label: string}[]) {
return arr;
}
export const PROPERTY_OPTIONS = checkArray([
{ value: "tag", label: "Tag" }, 
{ value: "composition", label: "Composition" },
{ value: "solvent", label: "Solvent" },
{ value: "allergen", label: "Allergen" },
{ value: "category", label: "Category" },
{ value: "other", label: "Other" },
]);
type PropertyOption = typeof PROPERTY_OPTIONS[number]
// type PropertyOption = {
//     value: "tag" | "composition" | "solvent" | "allergen" | "category" | "other";
//     label: string;
// }
interface CreatePropertyModalState {
type: PropertyOption
}

操场上联系

最新更新