개키우는개발자 : )

TypeScript type alias 본문

TypeScript/TypeScript

TypeScript type alias

DOGvelopers 2020. 1. 5. 18:57
반응형

광고 클릭은 개발자(저) 에게 큰 힘이 됩니다!!'ㅁ'

| 타입 스크립트 타입 별칭

 

타입에 직접 이름을 부여할 수 있습니다.

 

intersection type으로 User와 Action을 UserAction이라는 별칭을 type키워드를 사용하여 만들 수 있습니다. 

interface User {
    name : string;
}

interface Action{
    do() : void;
}

type UserAction = User & Action;

function createUserAction() : UserAction{
    return {
        do() {},
        name : ''
    }
}

 

 

union type 도 별칭으로 부여 가능하며 generic type 또한 별칭이 가능하다 

 

type StringOrNumber = string | number;
type Arr<T> = T[];
type P<T> = Promise<T>;

 

interface type처럼 특정 타입을 정의도 가능합니다.

type User2 = {
    name : string;
    login() : boolean;
}

class UserImpl implements User2{
    login(): boolean {
        throw new Error("Method not implemented.");
    }
    name : string;
}

 

유저의 상태 값을 확인할 때 유용하게 사용할 수 있는 방법 중 하나가 문자열을 union 방식으로 리터럴 하게 타입을 정할 수 있습니다.

type UserState = 'PENDING' | 'APPROVED' | 'REJECTED';

function checkUser(user: User2) : UserState {
    if(user.login()){
        return 'APPROVED'
    }else{
        return 'REJECTED'
    }
}

 

반응형

'TypeScript > TypeScript' 카테고리의 다른 글

TypeScript 인덱스 타입  (0) 2020.01.05
TypeScript intersection & union Types  (0) 2020.01.05
TypeScript 제네릭  (2) 2020.01.05
TypeScript 클래스-2  (0) 2020.01.05
TypeScript 클래스-1  (0) 2020.01.04
Comments