Front End/React

typescript 변수를 통한 객체 속성 접근

YJ_SW 2023. 1. 26. 21:43
728x90

변수를 통한 객체 속성 접근 - javascript

객체 속성을 변수를 통해 접근할 때 대괄호 표기법  [ ] 안에 변수를 넣어 접근하면 된다.

export class Route {
    id?: string;
    action?: string;
}

const setInfo = (field: any, id: string, value: any) => {
    let route = new Route(id);
    route[field] = value;
}

javascript 에서는 대괄호 표기법으로 [ ] 안에 변수를 넣어 사용해도 에러가 발생하지 않았다.

변수를 통한 객체 속성 접근 - typescript

하지만 TypeScript에서는 

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Route'.ts(7053)

이와 같은 에러가 발생한다.

해결방법

key oftype of 를 활용해 객체의 key임을 명시하면 된다.

// Solution 1: When the type of the object is known
route[field as keyof Route] = value;

// Solution 2: When the type of the object is not known
route[field as keyof typeof route] = value;

 

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

728x90