let x: number = 10;
let xPosition: number = 10;
x라는 변수의 타입은 number 타입이다. 하지만 이 x가 정확히 무엇을 뜻하는지 알기 어렵다.
x,y 좌표를 나타내는 숫자인지 아니면 다른 의미가 있는지 알기 어렵다.
xPosition과 같이 변수명에 의미를 부여하는 방법이 있지만, number 타입 자체에 의미를 부여하고 싶을 때 사용하는 것이 Type Alias 이다.
export type YesOrNo = 'Y' | 'N';
export type DayOfWeek = '일' | '월' | '화' | '수' | '목' | '금' | '토';
export enum DayOfTheWeek = {'일', '월', '화', '수', '목', '금', '토'};
const startDayOfWeek: DayOfWeek = '일'
export type Name = string;
export type Email = string;
export type Fun = () => string; // 파라미터 없이 return 값이 string인 함수
Interface는 Type Alias와 매우 유사하지만 문법이 다르다.
타입 지정
export interface User {
readonly id: number;
readonly name: Name; // type alias로 명시한 Name을 가져다가 쓸 수 있다.
email: string;
receiveInfo: boolean;
avtive: YesOrNo;
}
사용 코드
const appUser: User = {
id: 1,
name: 'guno',
email: 'bgo517@kk.com',
receiveInfo: false,
active: 'Y',
};
appUser는 User 인터페이스의 규격을 그대로 따라야한다.
export interface User {
address?: string;
};
address옆에 ?가 붙어 있으면 optional이라는 뜻이다.
객체를 만드는데 address라는 속성이 있어도 되고 없어도 된다는 뜻이다.
(?가 없는 변수명들은 필수적으로 들어가야한다.)
// 인터페이스
export interface User {
readonly id: number;
readonly name: Name;
email: string;
receiveInfo: boolean;
avtive: YesOrNo;
}
// 타입 별칭
export type User = {
readonly id: number;
readonly name: string
email: Email;
receiveInfo: boolean;
avtive: YesOrNo;
}
interface 와 type alias의 차이점은 '=' 의 유무이다.
interface는 이름이 중복되면 합쳐진 interface로 동작한다. 중복이 허용이 된다.
하지만 type alias는 이름이 중복되면 오류가 발생한다.
interface가 중복이 허용되지만 코드를 작성할 때, 분산되어 작성하는 것은 그렇게 좋지 않은 코드 스타일이다. (가독성의 저하(?))
export interface InterfaceUserProfile extends User {
profileImage: string;
github?: string;
twitter?: string;
};
User interface 속성이 반복적으로 사용될 때, 클래스의 상속과 유사하게 extends 키워드로 interface를 확장할 수 있다. InterfaceUserProfile 안에는 User 속성들을 포함시켜 User interface를 재활용할 수 있다.
export type TypeUserProfile = User & {
profileImage: string;
github?: string;
twitter?: string;
};
export type Color {...속성들};
export type Display {...속성들};
export type Geometry {...속성들};
export interface InterfaceStyle extends Color, Display, Geometry {
tagName: string;
};
export type TypeStyle = Color & Display & Geometry & {
tagName: string;
};
Color, Display, Geometry를 모두 확장한 Style interface가 만들어 지고 tagName 속성이 추가되는 식이다.
export interface numberObject {
[key: string]: number;
};
//실제 코드
const numValueObject = {
width: 300,
height: 200,
}
export interface GetApi {
(url: string, search?: string): Promise<string>
};
const getApi: GetApi = (url, search ='') => {
return new Promise(resolve => resolve('ok'));
};
()안에는 인자 값들이 들어가고 : 뒤에는 return 값을 서술하면 된다.
코드에 함수 규격을 사용하려면 함수 정의문이 아니라 함수 정의 표현식을 써야한다.
인터페이스와 타입 별칭은 많이 유사하다.
코드를 작성할 때, 자신이 원하는 스타일을 정해서 작성하면 된다.
데이터를 표현할 때는 타입 별칭을 쓰고 메소드, 구체적인 행위까지 포함된 데이터를 포괄하는 객체들을 표현할 때는 인터페이스를 쓴다.