타입스크립트 TypeScript

타입스크립트 심화 - 타입 결합 (유니온, 교차) / 인터페이스 / 제네릭

leexx 2023. 5. 16. 00:34

타입 결합

유니온 타입 (Union Type)

  • 두 개 이상의 타입을 허용하는 경우
  • 유니언에 있는 모든 타입에 공통인 멤버들에만 접근할 수 있음 (주의)
  • | 기호로 결합함
    • let myLet: type1 | type2 = value;
let union: string | number;
union = 'Hello type!';
union = 123;
union = false; // Error - TS2322: Type 'false' is not assignable to type 'string | number'.
function padLeft(value: string, padding: boolean | number) { }

let indentedString = padLeft("Hello world", true);
// @errors: 2339

interface Bird {
  fly(): void;
  layEggs(): void; // 공통
}

interface Fish {
  swim(): void;
  layEggs(): void; // 공통
}

declare function getSmallPet(): Fish | Bird;

let pet = getSmallPet();
pet.layEggs(); // 공통

// 두 개의 잠재적인 타입 중 하나에서만 사용할 수 있습니다.
pet.swim(); // X

 

교차 타입 (Intersection Type)

  • 여러 타입을 하나로 결합하여, 기존 타입들을 모두 합친, 단일 타입을 얻을 수 있음
  • & 기호로 결합함
    • type newType = type1 & type2
interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtworksData {
  artworks: { title: string }[];
}

interface ArtistsData {
  artists: { name: string }[];
}

// 이 인터페이스들은
// 하나의 에러 핸들링과 자체 데이터로 구성됩니다.

type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;

 

인터페이스 (Interface)

  • 여러 타입을 하나로 묶어서 쓸 수 있음 (유니온, 교차 보다 더 복합적으로)
  • extends 문법으로 기존의 타입을 바탕으로 새로운 타입을 만들 수 있음
  • 프로퍼티 문법
    • ?: 옵셔널 프로퍼티 (선택적 프로퍼티)
    • readonly: 읽기전용 프로퍼티
interface person {
    age: number;
    name: string;
    gender?: string; // optional 
    getAge: () => number; // 함수 타입 
    getName: () => string;
    readonly createdAt: string; // readonly
}

interface webDeveloper extends person {
    position: "front-end" | "back-end";
    company?: string;
    getPosition: () => string;
    getCompany?: () => string;
}

let leexx: webDeveloper = {
    age: 29,
    name: "lee-xx",
    position: "front-end",
    createdAt: "2023-05-15",
    gender: "female",
    company: "NAVER",
    getAge: function() { return this.age },
    getName: function() { return this.name },
    getPosition: function() { return this.position },
    getCompany: function () { return this.company }
};

console.log(leexx.getAge()) // 29
console.log(leexx.getName()) // "lee-xx"
console.log(leexx.getPosition()) // "front-end"
console.log(leexx.getCompany()) // "NAVER"

 

제네릭 (Generic)

  • 타입을 변수화 시킴
  • <T> 가 선언된 타입, 꼭 T가 아니어도 됨
function getText<T>(text: T): T {
    return text;
}

function getAge<A>(age: A): A {
    return age;
}

console.log(getText("name"));
console.log(getAge("29"));

 

참고자료