繁体   English   中英

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

[英]TypeScript: Constant array as type definition

我正在从事一个打字稿项目,并且在定义合适的类型方面有些挣扎。 语境:

我的项目中有以下常量:

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
}

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM