Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 버스분석
- 백준 10172
- DataFrame
- 백준 11718
- react #회원가입 #비밀번호비교
- useState
- getline
- 광명시버스분석
- plot in r
- 값삭제
- R데이터형태
- 10172
- 이스케이프시퀀스
- R 그래프
- 배열삭제
- 그래픽
- await
- 탈출문자
- vetor
- barplot in r
- 값추가
- barplot
- 이용현황분석
- 데이터분석
- 배열추가
- 백준
- React
- setstate
- 그대로 출력하기
- asynchronization
Archives
- Today
- Total
devlog_zz
typescript 변수를 통한 객체 속성 접근 본문
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 of 와 type 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;
728x90
'Front End > React' 카테고리의 다른 글
Comments