타입스크립트에서는 interface
와 type
을 사용하여 타입을 정의할 수 있습니다.
두가지 방법 중 필요에 따라 선택해서 사용하는것이 최선이라고 생각하며,
이번 글에서는 type
을 사용할 때 얻을 수 있는 장점과 특징에 대해서 간단하게 소개합니다.
type
을 사용하면 기존 타입에 새로운 이름을 지정할 수 있습니다.
이는 코드의 가독성을 높이고, 복잡한 타입을 간결하게 표현할 수 있게 해줍니다.
type MyType = string;
const value: MyType = "value";
type
을 사용하면 두 개 이상의 타입을 하나로 결합할 수 있습니다.
예를 들어, type StringOrNumber = string | number;
는 변수가 문자열 또는 숫자일 수 있음을 의미합니다.
type StringOrNumber = string | number;
const stringValue: StringOrNumber = "test";
const numberValue: StringOrNumber = 1;
const wrongValue: StringOrNumber = true; // 오류: Type 'boolean' is not assignable to type 'StringOrNumber'.
특정 값만을 타입으로 지정할 수 있습니다. 이를 통해 더 엄격한 타입 체크가 가능해집니다.
예를 들어, type Direction = "up" | "down" | "left" | "right";
는 Direction 타입이 네 가지 문자열 값 중 하나만 가질 수 있음을 의미합니다.
type Direction = "up" | "down" | "left" | "right";
const direction: Direction = "up";
const wrongDirection: Direction = "start"; // 오류: Type "start" is not assignable to type 'Direction'.
고정된 길이의 배열 타입을 정의하고, 각 요소의 타입을 지정할 수 있습니다.
예를 들어, type TupleType = [string, number];
는 첫 번째 요소가 문자열, 두 번째 요소가 숫자인 배열을 의미합니다.
특히 type
을 사용하면 이를 간결하게 표현 가능합니다.
type TupleType = [string, number];
const tuple: TupleType = ['test', 1];
const wrongTuple: TupleType = ["test", "Hello"]; // 오류: Type 'string' is not assignable to type 'number'.
interface
를 사용해도 튜플 타입을 정의할 수도 있지만, type을 사용하는 것보다 덜 직관적이고 복잡할 수 있으며, 개인적으로 type
을 사용하는걸 선호합니다.
interface MyTupleInterface {
0: number;
1: string;
}
const tuple: MyTupleInterface = [42, "hello"];