Type Alias
는 하나 이상의 타입을 조합해 별칭을 부여한다.
아래의 예시는 가장 간단하게 타입을 선언할 수 있는 방법이다.
짧고 간단한 코드에서는 문제가 없지만 규모가 큰 프로젝트의 경우 타입의 가시성이 좋기를 바란다.
let age: number = 20;
이때 사용하는 것이 Type Alias
이다.
type Age = number;
let age: Age = 20;
다양한 방법으로 타입을 선언할 수 있다.
type AType = string;
type BType = string | number | boolean;
type CType = {
name: string,
age: number,
isValid: boolean
};
let AUser: AType = 'A';
let BUser: BType = false;
let CUser: CType = {
name: 'miniddo',
age: 20,
isValid: true
};
interface
는 타입스크립트와 여러 객체를 정의하는 일종의 규칙이다.
인터페이스는 보통 앞에 I
를 별칭으로 사용한다.
interface IPalette {
id: number,
color: string,
isValid?: boolean
}
각 항목의 구분으로 ,
또는 ;
를 사용할 수 있으며, 없어도 무관하다.
또한 속성에 ?
를 붙이면 선택적 속성으로 정의할 수 있다.
const Red: IPalette = {
id: 0,
color: 'red',
isValid: true
}
const Orange: IPalette = {
id: 1,
color: 'orange'
}
// '?' 를 붙이지 않는 속성은 반드시 사용해야 한다.
// 'color' is declared here
const Pink: IPalette = {
id: 2
}
type Name = string;
type Age = number;
type multi = string | number | boolean;
type Name = string;
const name: Name = 1; // Type 'number' is not assignable to type 'string'
interface IUser {
name: string,
age: number
};
const user: IUser = {
name: 'miniddo',
age: '20' // The expected type comes from property 'age' which is declared here on type 'IUser'
};
extends
키워드로 확장할 수 있다.interface Shape {
color: string
};
interface Square extends Shape {
width: number,
height: number
}
const mySquare: Square = {
color: 'red',
width: 10,
height: 15
}