체인의정석

typescript에서 enum에 string을 인덱스로 썼을 때 발생하는 문제 해결 본문

개발

typescript에서 enum에 string을 인덱스로 썼을 때 발생하는 문제 해결

체인의정석 2021. 7. 22. 17:39
728x90
반응형

 

https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b

 

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

Trying out TypeScript for a React project and I'm stuck on this error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; tra...

stackoverflow.com

// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];

// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];

// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
  obj[key];

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

 

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

 

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

 

https://www.angularjswiki.com/angular/how-to-convert-a-string-to-enum-in-typescript-or-angular/

 

How To Convert a string to Enum in Typescript/Angular | Angular Wiki

To convert string to Enum in Typescript or angular follow the below steps. 1.Pass the given string to Enum object as a key. 2.If the string is part of the enum name entry the value will be returned. 3.And then cast it to the enum object to get enum type of

www.angularjswiki.com

다음 글을 참고하여 해결하였다.

 

원래 코드

// Change string to LegalPersonNameTypeCode
export function toLegalPersonNameTypeCode(legalPersonNameIdentifierType: string) {
  if (LegalPersonNameTypeCode[legalPersonNameIdentifierType]) {
    return LegalPersonNameTypeCode[legalPersonNameIdentifierType];
  }
  throw new Error(`${legalPersonNameIdentifierType} must be one of 'LEGL','SHRT', 'TRAD' `);
}

 

수정한 코드

// Change string to LegalPersonNameTypeCode
export function toLegalPersonNameTypeCode(legalPersonNameIdentifierTypeParam: string) {
  const legalPersonNameIdentifierType: LegalPersonNameTypeCode = (<any>legalPersonNameIdentifierTypeParam)[
    legalPersonNameIdentifierTypeParam
  ];

  if (legalPersonNameIdentifierType) {
    return legalPersonNameIdentifierType;
  }
  throw new Error(`${legalPersonNameIdentifierType} must be one of 'LEGL','SHRT', 'TRAD' `);
}

타입을 단순하게 string으로만 지정해 주는 것이 아니라 더 자세히 지정해 주어야 오류가 나지 않는다.

 

728x90
반응형
Comments