TypeScript

[TypeScript] 타입스크립트 타입

깅민 2025. 5. 23. 16:35

1. 유니온

유니온 타입을 사용하면 변수 하나를 여러 가지 타입으로 지정할 수 있습니다.

let uni: number | string | boolean = 10;
printUni(uni);
uni = "hello";
printUni(uni);
uni = true;
printUni(uni);

function printUni(value: number | string | boolean): void {
  if (typeof value === "number") {
    console.log(value);
  } else if (typeof value === "string") {
    console.log(value);
  } else if (typeof value === "boolean") {
    console.log(value);
  }
}

 

2. 별칭

타입 별칭은 변수의 타입을 정의할 때 사용할 수 있습니다.

같은 스코프 내에서는 같은 이름을 사용할 순 없습니다.

2-1.

자주 사용하는 타입은 이렇게 만들 수 있습니다.

기존의 타입을 넣고 추가로 타입을 만들수도 있습니다.

type t = number | string | boolean;

type addT = t | null;

let value: t = 10;
value = "a";
value = true;
value = null; // 에러

let nullableValue: addT = null;
nullableValue = 10;
nullableValue = "nullable";
nullableValue = true;
nullableValue = undefined; // 에러

 

2-2. 인터섹션 타입

type User = {
    id: number,
    name: string
};

const user: User = {
    id: 1,
    name: "a"
};

 

2-2-1. &

인터섹션 타입은 & 를 사용해 두 타입을 합쳐서 타입을 정의합니다.

 

type shirt = {
  price: number;
};
type info = {
  color: string
}

type shirtInfo = shirt & info;

const poloShirt: shirtInfo = {
  price: 1000,
  color: "red"
}

 

3. 인덱스 시그니처

타입을 정의할 때 그 개수가 1000개로 많아져야 한다고 하면 어떻게 할까요?

1000개를 다 작성해야 할 것입니다.

type code = {
  a: string,
  b: string,
  // ...(1000개)
}

 

인덱스 시그니처를 사용하면 이렇게만 작성하면 됩니다.

key가 string 타입이고

value가 string 타입인

모든 프로퍼티를 포함한다는 타입입니다.

type code = {
  [key: string]: string
}

 

추가로 반드시 필요한 타입이 있다면

직접 넣으면 됩니다.

 

type code = {
  [key: string]: string;
  require: string;
}

 

두 타입은 같아야 합니다. (string, string)

 

4. 리터럴 타입

한정적인 타입을 만들 수 있습니다.

let shirt: "polo" = "polo";

shirt = "polo2"; // 에러

 

type size = "small" | "medium" | "large";

let shirt: size = "small";
let bigShirt: size = "big"; // 에러

 

5. 함수 타입

함수도 타입으로 사용할 수 있습니다.

 

첫 번째 함수에서 타입은 (message: string) => string 입니다.

 

type1 처럼 지정할 수도 있고

 

type2 처럼 객체의 속성으로 지정할 수도 있습니다.

function msg(message: string): string {
  console.log(message);
  return message;
}
const fn1 = msg;

// 타입은 (message: string) => string

type type1 = (message: string) => string;
const fn2: type1 = msg;
fn2("test1");

type type2 = {
  (message: string): string;
};
const fn3: type2 = msg;
fn3("test2");