您遇到的第一个问题是属性的类型实际上都是string,而不是您可能期望的字符串文字类型。为了解决这个问题,我们可以使用类型断言:
export const QuantityModes = {
POSITIVE: 'POSITIVE' as 'POSITIVE',
NEGATIVE: 'NEGATIVE' as 'NEGATIVE',
ANY: 'ANY' as 'ANY',
};
使用辅助函数提示编译器我们需要类型文字:
export const QuantityModes = (<T extends { [P in keyof T]: P }>(o: T)=> o)({
POSITIVE: 'POSITIVE',
NEGATIVE: 'NEGATIVE',
ANY: 'ANY',
})
或者,从 3.4(尚未发布)开始,您可以写 as const:
export const QuantityModes = {
POSITIVE: 'POSITIVE',
NEGATIVE: 'NEGATIVE',
ANY: 'ANY',
} as const
您可以键入相对于另一种类型的类型,但语法不同。首先,如果你想访问属性的类型,语法是type['propName'](也称为index type query)。但是你想访问一个常量的类型,你需要使用typeof const。所以你可以写:
export type QuantityMode = typeof QuantityModes["POSITIVE"] | typeof QuantityModes["NEGATIVE"] | typeof QuantityModes["ANY"];
你也可以使用 union 来简化一点,结果相同:
export type QuantityMode = typeof QuantityModes["POSITIVE" | "NEGATIVE" | "ANY"];
如果联合包含所有属性名称,那么我们可以只使用keyof type 来获取类型内所有属性名称的联合(确保所有未来添加的内容也会自动添加到类型中)
export type QuantityMode = typeof QuantityModes[keyof typeof QuantityModes];
由于在这种情况下属性名称和属性类型是相同的,我们甚至可以只使用keyof:
export type QuantityMode = keyof typeof QuantityModes;