如果你只是像上面那样声明MenuOptions,编译器会倾向于将值类型推断为string[],而不是文字元组。如果您需要访问这些文字,那么您将需要更改声明对象的方式。当 TypeScript 3.4 于 2019 年 3 月发布时,您将能够使用 const context 来提示编译器推断可能的最窄类型,如下所示:
const MenuOptions = {
Project: ["new", "open", "close"],
File: ["create", "edit"]
// ...
} as const; // only works in TS3.4+
在此之前,您可以使用如下辅助函数来指导推理:
type Narrowable = string | number | boolean | undefined | null | void | {};
const tuple = <T extends Narrowable[]>(...t: T)=> t;
const MenuOptions = {
Project: tuple("new", "open", "close"),
File: tuple("create", "edit")
// ...
};
在任何一种情况下,您想要的类型都在上面给出为
type MenuOption = (typeof MenuOptions)[keyof typeof MenuOptions][number];
让我们将其分解为步骤并为中间类型命名。你取的是MenuOptions的类型:
type TypeofMenuOptions = typeof MenuOptions;
// type TypeofMenuOptions = {
// Project: ["new", "open", "close"];
// File: ["create", "edit"];
// }
查找其值类型的联合
type MenuOptionsValues = TypeofMenuOptions[keyof TypeofMenuOptions];
// type MenuOptionsValues = ["new", "open", "close"] | ["create", "edit"]
并查找其数字索引属性(如果您有一个类型 (A | B)[K],则它被评估为 A[K] | B[K])
type MenuOption = MenuOptionsValues[number];
// type MenuOption = "new" | "open" | "close" | "create" | "edit"
这让你得到了你正在寻找的字符串文字的联合。
好的,希望对您有所帮助。祝你好运!