-
data 를 typescript enum 으로 매칭하기프로그래밍/Javascript 2021. 10. 14. 13:30
A1. To convert a string to Enum in Typescript follow the below steps
- Pass the given string to Enum object as a key
- If the string is part of the enum name entry the value will be returned
- And then cast it to the enum object to get enum type of string
I have a created enum object of type Day, which represents time of Day
enum Day { BeforeNoon = "AM", AfterNoon = "PM", }
and I have a string variable which has value BeforeNoon. We will get the enum value by passing the string to enum object
const beforeNoon: string = "BeforeNoon"; const enumValue = Day["BeforeNoon"];
If the string key does not exists in enum object it will give Property does not exist on type error
const enumValue = Day["BeforeNoon1"]; // Property 'BeforeNoon1' does not exist on type 'typeof Day'
What if I pass variable instead of actual string. we will get Element implicitly has an 'any' type ... To avoid this error we need to cast it to enum object as shown below
const enumValue = (<any>Day)[beforeNoon]; const enumValue: Day = (<any>Day)[beforeNoon];
- 서버에서 받아온 string data 를 정의해둔 enum type 으로 바꾸기 위해 위 A1 을 참고해 다음과 같이 구현하였다
// types.ts export enum StatusDirection { in = '입금', out = '출금', } export enum StatusTransaction { pending = '진행중', confirmed = '완료', cancelled = '취소', }
const getTransActions = (account: IAccountInfo) => { const { transactions } = account; const transactionsForTable = transactions.map((transaction) => ({ type: (<any>StatusDirection)[transaction.direction], status: (<any>StatusTransaction)[transaction.status], ..... })); ..... };
- 원래는 select 에 들어갈 { value: '', label: '' } 형태로 만들기 위해 아래의 코드와 같이 사용하였다
const getUserCrypto = (user: IUserInfo): void => { const userCryptos = user?.wallets .map((wallet) => ({ value: wallet.cryptoType })) .map((crypto) => ({ ...crypto, label: (<any>CryptoType)[crypto.value] })); setUserCryptos(userCryptos); };
- 그런데 중복된 crypto 값을 없애고 출력하려다 보니 filter 메소드를 사용해야 해서 수정하였다. wallet 정보에서 crytoType 만 담은 array 를 만든다. 그 array 에서 중복을 제거한 후, { value: '', label: '' } 형태로 바꿔준다
const getUserCrypto = (user: IUserInfo): void => { // const userCryptoType = user?.wallets.map((wallet) => ({ value: wallet.cryptoType })); const userCryptoType = user?.wallets.map((wallet) => wallet.cryptoType); const userCryptos = userCryptoType ?.filter((crypto, idx) => userCryptoType.indexOf(crypto) === idx) .map((crypto) => ({ value: crypto, label: (<any>CryptoType)[crypto] })); // .map((crypto) => ({ ...crypto, label: (<any>CryptoType)[crypto.value] })); setUserCryptos(userCryptos); };
Ex. Typescript Enum to Array. Considering a key/value enum, you can use the Object.entries to extract the data and create the array
export enum StatusDirection { in = "입금", out = "출금", } export const StatusDirectionList: { key: string; value: string; }[] = Object.entries(StatusDirection) .map(([key, value]) => ({ key, value }));
But, if you have an enum without key=value association? In this case, you need to get the values and filter only strings:
export enum Status { activated, suspended, } export const StatusList: { value: string; }[] = Object.values(Status) .filter((value) => typeof value === "string") .map((value) => ({ value: value as string }));
It was necessary because each value without an association generates two values: the key itself and the value (a number)
Ex. Typescript enum to object array. A tricky bit is that Typescript will 'double' map the enum in the emitted object, so it can be accessed both by key and value
export enum Status { activated, suspended, } export enum Status { activated = 0, suspended = 1, }
will be emitted as
{ activated: 0, suspended: 1, 0: 'activated', 1: 'suspended', }
So you should filter the object first before mapping
const IsNumber = value => isNaN(Number(value)) === false; // turn Enum into Array function ToArray(enum) { return Object.keys(enum) .filter(IsNumber) .map(key => enum[key]); }
Ex. d
참고
더보기https://www.angularjswiki.com/angular/how-to-convert-a-string-to-enum-in-typescript-or-angular/
https://dev.to/joaozitopolo/typescript-enum-to-array-42jg
https://stackoverflow.com/questions/43100718/typescript-enum-to-object-array
https://stackoverflow.com/questions/17380845/how-do-i-convert-a-string-to-enum-in-typescript
.
'프로그래밍 > Javascript' 카테고리의 다른 글
webpack (0) 2021.10.25 material-ui 사용기 createTheme, font, style, select (0) 2021.10.15 Array, Object 관련 메소드 (0) 2021.09.07 js / jquery 에서의 click 이벤트 바인딩 (0) 2021.05.03 getElementsByClassName() / getElementsByTagName() (0) 2020.12.25