본문 바로가기
TypeScript

[TypeScript] object index signature (인덱스 서명)

by 딩박사 2023. 11. 1.
반응형

* 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다.


interface UserType {
    name : string,
    age : string,
    address : string
}

let user :UserType = {
    name : 'hoo',
    age : '27',
    address : 'seoul'
}

▲ object에 타입을 일일이 타입을 지정해줘야 하는 불편함이 있다.

 

 

interface UserType {
    [key : string] : string,
}

let user :UserType = {
    name : 'hoo',
    age : '27',
    address : 'seoul'
}

index signature 를 쓰면 { [Key: T]: U } 형식으로 객체가 Key를 여러 개 가질 수 있으며 Key와 매핑되는 Value를 가지는 경우 사용한다.
1. 타입을 미리 만들고 싶은데 object자료에 어떤 속성들이 들어올 수 있는지 아직 모르는 경우 사용
2. 타입지정할 속성이 너무 많은 경우 사용

 

 

interface UserType {
    [key : number] : string,
}

let user :UserType = {
    0 : 'hoo',
    1 : '27',
    2 : 'seoul'
}

▲ 속성이름이 숫자인 경우에도 index signature를 사용가능하다.

 

 

interface FontType {
    'font-size' : {
    	'font-size' : {
            'font-size' : number;
        }
    }
}

let css :FontType = {
    'font-size' : {
    	'font-size' : {
            'font-size' : 20
        }
    }
}

속성명이 재귀적으로 중복속성에 대해 타입을 선언할 땐

 

 

interface FontType {
    'font-size' : FontType | number
}

let css :FontType = {
    'font-size' : {
    	'font-size' : {
            'font-size' : 20
        }
    }
}

 

‘font-size' : MyType -> {'font-size' : MyType} 라는 의미로 recursive 타입으로 선언할 수 있다. 

맨 마지막에 20이 와야 하므로 FontType | number로 설정한다.

 

 

 

결론

Typescript에 대해서 공부하면 할수록 타입을 일괄 적요할 수 있는 다양한 기능이 있는 것 같다. 속성명이 재귀적으로 중복속성을 띌 경우 recursive 타입으로 선언하자!!

반응형

댓글