Index signatures
객체(object)의 속성을 동적으로 정의하는 방법 중 하나이다. 객체가 특정 속성을 가질 때마다 해당 속성의 유형을 지정할 수 있다.
일반적으로 객체의 속성은 사전에 정의되어야 하지만 때로는 런타임 시에 정의되는 동적인 속성이 필요할 수 있다. 이런 경우 index signatures를 사용하여 객체의 속성을 유연하게 처리할 수 있다.
- index signatures 기본구문
{
[propertyName: string]: propertyType;
}
여기서 [propertyName: string]은 객체의 속성 이름을 나타내며, 'propertyType' 은 해당 속성의 유형을 나타낸다. 이러한 색인 서명을 사용하면 객체의 속성이 사전에 정의되지 않은 경우에도 TypeScript가 해당 속성을 인식할 수 있다.
- 동적인 속성을 갖는 객체 정의
interface Person {
[key: string]: string | number;
}
const person: Person = {
name: "John",
age: 30,
// Additional dynamic properties
city: "New York",
occupation: "Engineer"
};
위의 예제에서 'person' 인터페이스는 string 유형의 키로 string 또는 number 타입의 값이 있는 객체를 정의한다. 이를 통해 person 객체는 name과 age 속성 외에도 다른 동적인 속성들을 가질 수 있다.
쉽게 말하면 { 모든 속성 : string or number} 랑 동일하다.
interface StringOnly {
age : number, ///에러남
[key: string]: string,
}
interface StringOnly {
age : string, ///가능
[key: string]: string,
}
위의 예제에서 에러가 나는 이유는 { 모든 속성 : string, age: number} 이 논리가 맞지 않아서 이다. 쉽게 말해서 모든 속성을 string으로 지정해줬는데 age가 number로 지정할 수 없는 것이다.
interface StringOnly {
age : number, ///가능
[key: string]: string | number,
}
하지만 위의 예제는 가능하다. 모든 속성이 string or number이기 때문에 age만 number로 지정하는 것은 가능하다.
array 형태
interface StringOnly {
[key: number]: string,
}
let obj :StringOnly = {
0 : 'kim'
1 : '20',
2 : 'seoul'
}
[] 안에 key 값의 타입을 number로 지정할 수 있다.(단, [] 안에는 string 또는 number만 가능)
Recursive Index Signatures
let obj = {
'font-size' : {
'font-size' : {
'font-size' : 14
}
}
}
중첩 object 들을 한번에 타입 지정하려면
interface MyType {
'font-size' : {
'font-size' : {
'font-size' : number
}
}
}
위와 같이 해도 되지만
interface MyType {
'font-size': MyType | number
}
let obj :MyType = {
'font-size' : {
'font-size' : {
'font-size' : 14
}
}
}
위와 같은 방법을 써도 된다.
'👨💻 TypeScript' 카테고리의 다른 글
TypeScript - if else in types (0) | 2024.03.20 |
---|---|
TypeScript - type mapping (0) | 2024.03.20 |
TypeScript - implements (0) | 2024.03.19 |
TypeScript - declare (0) | 2024.03.19 |
TypeScript - TypeScript + Redux (0) | 2024.03.19 |