programing

유형 스크립트의 열거 문자열에 캐스팅

mailnote 2023. 8. 19. 10:32
반응형

유형 스크립트의 열거 문자열에 캐스팅

RESTful 서비스에서 다음 데이터를 얻습니다.

[
  {
    "id": 42,
    "type": 0,
    "name": "Piety was here",
    "description": "Bacon is tasty, tofu not, ain't nobody like me, cause i'm hot...",
  }...

그리고 저는 이 클래스와 매핑하고 있습니다.

export enum Type {
  Info,
  Warning,
  Error,
  Fatal,
}


export class Message{
  public id: number;
  public type: Type:
  public name: string;
  public description: string;
}

그러나 Angular2의 'type'에 액세스하면 int 값만 표시됩니다.하지만 저는 문자열 값을 받고 싶습니다.

예:

'message.type=0'
{{message.type}} => should be Info
'message.type=1'
{{message.type}} => should be Warning

TypeScript의 열거형은 런타임에 숫자입니다.message.type될 것이다0,1,2또는3.

문자열 값을 가져오려면 해당 숫자를 인덱스로 열거형에 전달해야 합니다.

Type[0] // "Info"

따라서 이 예제에서는 다음 작업을 수행해야 합니다.

Type[message.type] // "Info" when message.type is 0

문서

TypeScript의 Enums는 런타임에 다음과 같은 속성을 가진 객체입니다.int -> string그리고 부터string -> int가능한 모든 값에 대해

문자열 값에 액세스하려면 호출해야 합니다.

Type[0] // "Info"

연결된 호출로 인해 다음과 같은 결과가 발생할 수 있으므로 올바른 유형을 속성 액세스 장치에 전달하고 있는지 확인합니다.

Type[Type.Info] // "Info"
Type[Type[Type.Info]] // 0
Type["Info"] // 0
Type[0] // "Info"

내 생각엔

{{message.type}}

열거형이 아닌 매핑된 값만 얻을 수 있습니다.다음 코드를 사용해 보십시오.

{{TYPE[message.type]}}

유형 스크립트에서 열거형이 작동하는 방식은 다음과 같습니다.

   enum PrintMedia {
      Newspaper = 1,
      Newsletter,
      Magazine,
      Book
    }

  PrintMedia.Magazine;            // returns  3
  PrintMedia["Magazine"];         // returns  3
  PrintMedia[3];                  // returns  Magazine
  PrintMedia[PrintMedia.Magazine];// returns  Magazine

언급URL : https://stackoverflow.com/questions/42299257/cast-int-to-enum-strings-in-typescript

반응형