簡體   English   中英

如何獲取枚舉值 typescript 類型

[英]How to get enum values typescript type

不確定如何獲取枚舉值 typescript 類型:

沙盒

// enum is generated and i can't change it
 
 enum UserRole {
  Alfa = 'alfa',
  Beta = 'beta',
  Helper = 'helper'
}

// i need to get type like this:
type Role = 'alfa' | 'beta' | 'helper'

// to use it like this:
const role: Role = 'alfa'

// what i got so far
type A1 = keyof typeof  UserRole  // "Alfa" | "Beta" | "Helper"
type A2 = Record<UserRole, string> 
/*{
    alfa: string;
    beta: string;
    helper: string;
}*/


// intresting that if i use A2 type defined by hand it will work
type X = {
    alfa: string;
    beta: string;
    helper: string;
}

const x: keyof X = 'alfa'

// but if i try to get this type from A2 directly it will jump back to UserRole and wont work
const y: keyof A2 = 'alfa'

不確定如何獲取枚舉值 typescript 類型:

沙盒

// enum is generated and i can't change it
 
 enum UserRole {
  Alfa = 'alfa',
  Beta = 'beta',
  Helper = 'helper'
}

// i need to get type like this:
type Role = 'alfa' | 'beta' | 'helper'

// to use it like this:
const role: Role = 'alfa'

// what i got so far
type A1 = keyof typeof  UserRole  // "Alfa" | "Beta" | "Helper"
type A2 = Record<UserRole, string> 
/*{
    alfa: string;
    beta: string;
    helper: string;
}*/


// intresting that if i use A2 type defined by hand it will work
type X = {
    alfa: string;
    beta: string;
    helper: string;
}

const x: keyof X = 'alfa'

// but if i try to get this type from A2 directly it will jump back to UserRole and wont work
const y: keyof A2 = 'alfa'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM