打字稿:来自枚举的字符串文字联合类型 [英] Typescript: string literal union type from enum

查看:25
本文介绍了打字稿:来自枚举的字符串文字联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从枚举中获取字符串文字联合.

I'd like to get a string literal union from an enum.

对于这个枚举......

For this enum…

enum Weekday {
    MONDAY = 'mon',
    TUESDAY = 'tue',
    WEDNESDAY = 'wed'
}

……我想得到这个:

type WeekdayType = 'mon' | 'tue' | 'wed';

我尝试了 typeof keyof Weekday 但结果是 '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.

我该怎么做?

推荐答案

参见 TS4.1 ANSWER:

type WeekdayType = `${Weekday}`;


TS-4.1 之前的回答:


PRE TS-4.1 ANSWER:

这不能以编程方式完成...您正在尝试转换类型 Weekday,即 Weekday.MONDAY |Weekday.TUESDAY |Weekday.WEDNESDAY,类型为 WeekdayType,即 mon"|周二"|结婚".这种转换是一种加宽的形式,因为WeekdayWeekdayType的子类型:

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.

那么,解决方法?也许您实际上并不需要 enum,但可以使用属性值为字符串文字的对象:

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],

如果你检查它,名为 Weekdayvalue 就像一个枚举对象:

If you inspect it, the value named Weekday behaves like an enum object:

console.log(Weekday.TUESDAY); // tue

虽然名为 Weekdaytype 的行为类似于字符串值的并集 mon"|周二"|wed" 你正在调用 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 类型区分开来.它与实际的enum(包括类型,例如Weekday.MONDAY,您必须将其表示为繁琐的typeof Weekday.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!

这篇关于打字稿:来自枚举的字符串文字联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆