반응형
유형 스크립트의 열거 문자열에 캐스팅
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
반응형
'programing' 카테고리의 다른 글
| IBNSLayoutConstraint라는 클래스를 인스턴스화할 수 없습니다. (0) | 2023.08.19 |
|---|---|
| PowerShell의 Get-Content, Regex 및 Set-Content 다음에 모든 새로운 라인이 삭제되는 이유는 무엇입니까? (0) | 2023.08.19 |
| imshow의 수치가 너무 작습니다. (0) | 2023.08.14 |
| 윈도우즈에서 ssh-agent와 함께 git 사용 (0) | 2023.08.14 |
| 동적으로 생성된 요소에 날짜 선택기() 배치 - JQuery/JQueryUI (0) | 2023.08.14 |