重新研究的类型非常接近。 E
。 union union <>E 具体来说,作为字面类型的特殊subtype处理,因此,你可以仅作书面处理,例如,>cherries>
inplace of E.C
。
In some sense, the whole point of an enum
is to abstract away the actual literal types of the values. If you actually care about these literal types, you might want to avoid enum
entirely in favor of an object of the same shape:
const EObject = {
A: "apple",
B: "banana",
c: "cherries"
} as const;
type EKey = keyof typeof EObject;
// type EKey = "A" | "B" | "c"
type EValue = (typeof EObject)[EKey];
// type EValue = "apple" | "banana" | "cherries"
as const
请汇编者跟踪标值的字面值的描述,以便你能够轻易地提取钥匙和价值类型。
但是,也许你的使用情况不允许这样做。
If you really want to extract "apple" | "banana" | "cherries"
from E
, you can use template literal types to ask "what happens when I serialize E
as a string
"?
enum E {
A = "apple",
B = "banana",
C = "cherries"
}
type EValue = `${E}`;
// type EValue = "apple" | "banana" | "cherries"
这产生了理想的结合。 请注意,如果<条码>E> 是全数<>。 最后,请附上数字的缩略语。
enum F {
D = "durian",
E = 123,
F = "figs",
G = 456
}
type FValueOops = `${F}`
// type FValueOops = "durian" | "figs" | "123" | "456"
If such things matter you could more effort teasing numeric and string literals out:
type EnumToLiteral<T extends string | number> =
T extends string ? `${T}` : `${T}` extends `${infer N extends number}` ? N : never;
type FValue = EnumToLiteral<F>;
// type FValue = "durian" | 123 | "figs" | 456
但是,在进行这种分类之前,我建议采用<条码>作为星号/代码>而不是<条码>。
Playground link to code