Typescript
Typescript에서 객체의 프로퍼티의 key값에 접근할때 string으로 접근 할 수 없다
Dev갱이
2024. 5. 30. 18:14
728x90
const obj = {
foo: 'hello'
}
let propertyName = 'foo';
console.log(obj[propertyName]);
TypeScript는 기본적으로 객체의 프로퍼티를 읽을 때, string 타입의 key 사용을 허용하지 않는다.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: string; }'. No index signature with a parameter of type 'string' was found on type '{ foo: string; }'.(7053)
에러가 발생한다.
key값으로 올 수 있는 것은 string Literal type 이기 때문이다.
const obj = {
foo: 'hello'
}
const propertyName = 'foo';
console.log(obj[propertyName]); // ok
const propertyName = 'foo' 로 바꿔주면 propertyName은 foo string 리터럴타입으로 추론되어서 정상적으로 접근 가능해진다.
하지만 만약에 obj의 키값이 유동적인 key값이 올 수 있게 만들려면 그때 Index Signature 를 사용하면 된다.
type ObjType = {
foo: string;
[key: string]: string;
};
const obj: ObjType = {
foo: 'hello',
};
const propertyName = 'foo';
const propertyName2 = 'bar';
console.log(obj[propertyName]); // ok
console.log(obj[propertyName2]); // ok
Reference
https://soopdop.github.io/2020/12/01/index-signatures-in-typescript/
TypeScript에서 string key로 객체에 접근하기
TypeScript에서 string key로 객체에 접근하기
soopdop.github.io
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
728x90