typescript에서는 type이라는 키워드로 사용자 정의 유형을 생성할 수 있다.
type a = {
name: string; // key : type
family: string[];
};
const A : a ={ //type을 a로 정의
name: Micle,
family: [Tom, Ada]
};
//먼저 두개의 커스텀 타입 정의
type Alice = {
job: string;
grade: number;
};
type student= {
grade: number;
techer: Person;
};
// 객체 정의
const techer: Alice = {
job: 'techer',
grade: 1
}
const Micle : student = {
name: 'Micle',
grade: 1,
Alice,
}
//객체 리터럴 내부에서 직접 설정
const Micle: student = {
name: Micle,
grade: 1,
Alice: {
job:'techer',
grade:1
}
};
위에서는 custom type의 유형들을 생략할 수 없었다.
하지만 ? 를 추가하면 생략이 가능하게 되는데 아래 예시를 보자.
type Who = {
name: string;
age: number;
school?: string;
phoneNumber?: string;
};
const a : Who = {
name : 'Micle',
age: 10,
phoneNumber: '11111111',
};
// 이렇게 선택적 속성을 선언하고 해당 속성을 생략해도 오류가 일어나지 않는다.
필드 수의 제한이 없는 유형을 만들려고 할때 위처럼 일일이 지정하는 방법으로는 불가능 하다는 것을 알 수 있다. 그렇다면 어떻게 해야할까. 아래 코드를 보자
type Data = {
[key: string]: any; // [key : key의 type] : value의 타입 , Data 안에 들어가있는 키들은 string 이며 vlaue들은 any타입을 갖도록 설정한것.
};
const AData : Data = {
AA : 'a' ,
AB : 'b' ,
AC : 100 ,
};