问题描述
我想从枚举中获取字符串文字联合。
I'd like to get a string literal union from an enum.
对于此枚举……
enum Weekday {
MONDAY = 'mon',
TUESDAY = 'tue',
WEDNESDAY = 'wed'
}
…我想得到这个:
type WeekdayType = 'mon' | 'tue' | 'wed';
我尝试了工作日类型的键
,但是结果在'MONDAY'中| 星期二 | 星期三
。感觉该解决方案可能与映射类型有关,但是我似乎无法将其包裹住。
I tried typeof keyof Weekday
but that resulted in 'MONDAY' | 'TUESDAY' | 'WEDNESDAY'
. Feel like the solution might have to do with mapped types but I can't seem to wrap my head around it.
我该怎么做?
推荐答案
无法通过编程方式完成...您正尝试将类型转换为平日
,即 Weekday.MONDAY | Weekday.TUESDAY | Weekday.WEDNESDAY
,类型为 WeekdayType
,即 mon | 星期二 | 星期三
。此转换是扩大的一种形式,因为工作日
是 WeekdayType
的子类型:
This can't be done programmatically... you're trying to convert the type Weekday
, which is Weekday.MONDAY | Weekday.TUESDAY | Weekday.WEDNESDAY
, to the type WeekdayType
which is "mon" | "tue" | "wed"
. This conversion is a form of widening, since Weekday
is a subtype of WeekdayType
:
type WeekdayExtendsWeekdayType =
Weekday extends WeekdayType ? true : false
// type WeekdayExtendsWeekdayType = true
不幸的是编译器没有给你一个从枚举类型中删除枚举性质并留下普通文字类型的句柄。
Unfortunately the compiler doesn't give you a handle to remove an "enum"-ness from the enum type and leave you with plain literal types.
那么,解决方法是?也许您实际上并不需要枚举
,但可以处理其属性值为字符串文字的对象:
So, workarounds? Maybe you don't actually need an enum
, but can make do with an object whose property values are string literals:
const lit = <V extends keyof any>(v: V) => v;
const Weekday = {
MONDAY: lit("mon"),
TUESDAY: lit("tue"),
WEDNESDAY: lit("wed")
}
type Weekday = (typeof Weekday)[keyof typeof Weekday],
它,名为平日
的值的行为类似于枚举对象:
If you inspect it, the value named Weekday
behaves like an enum object:
console.log(Weekday.TUESDAY); // tue
而 type 名为 Weekday
的行为类似于字符串值 mon |的并集。 星期二 |您正在呼叫的结婚
WeekdayType
:
while the type named Weekday
behaves like the union of string values "mon" | "tue" | "wed"
that you were calling WeekdayType
:
const w: Weekday = "wed"; // okay
const x: Weekday = "xed"; // error
因此,在此替代方法中,没有枚举作用,因此不需要区分类型 Weekday
和类型 WeekdayType
。它与实际的枚举
(包括类型如 Weekday.MONDAY
)略有不同, (您必须将其表示为Weekday.MONDAY的繁琐 type.MONDAY
或为其创建不同的类型别名),但是它的行为可能相似得足够有用。
So in this workaround, there is no "enum"-ness, and therefore no need to distinguish the type Weekday
from the type WeekdayType
. It's a little different from an actual enum
(which includes types like Weekday.MONDAY
, which you'd have to represent as the cumbersome typeof Weekday.MONDAY
or create a different type alias for it), but it might behave similarly enough to be useful. Does that work for you?
希望有帮助。祝你好运!
Hope that helps. Good luck!
这篇关于打字稿:枚举中的字符串文字联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!