웹 개발/Typescript

type vs. interface

투자유v 2022. 1. 4. 11:15
728x90
// 5. type alias vs. interface
// 5-1. function
interface IFunction {
    (name: string, age?: number): void;
}

type tFunction = (name: string, age?: number) => void;

// 5-2. array
type tArray = string[];
interface IArray {
    [index: number]: string;
}

// 5-3. intersection
interface ErrorHandling {
    success: boolean;
    error?: { message: string };
}

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

type ArtistsResponseType = ArtistData & ErrorHandling;

interface IArtistsResponse extends ArtistData, ErrorHandling {};

let tar: ArtistsResponseType;
let iar: IArtistsResponse;

// 5-4. union type (only type)
type stringOrNumber = string | number;

// 5-5. declaration merge(only interface)
interface DeclarationMerge {
    name: string;
}
interface DeclarationMerge {
    age?: number;
}

둘 다 타입을 정의하는 방법인데, interface는 타입을 새로 만드는 것 같고, type은 이미 있는 타입들을 조합해서 이름을 정하는 것 같다.