TIL 230430 type / interface

Chae·2023년 4월 30일

TIL 2304

목록 보기
8/8
post-thumbnail

🎆 오늘 한 것

  • 노마드 TS 강의
  • 리액트 강의 복습
  • 노마드 캐럿마켓 강의



✨ TS - type / interface

🎆 type

Type은 TS에서 값을 나타내는데 사용되며, 기본 타입 (boolean, string, number 등)과 객체나 함수 등의 복잡한 타입을 정의할 수 있다.

type MyType = {
  name: string;
  age: number;
  isStudent: boolean;
};

🎆 interface

Interface는 객체의 구조와 타입을 정의할 때 사용된다. Type과 마찬가지로 기본 타입과 객체, 함수 등을 정의할 수 있음

interface MyInterface {
  name: string;
  age: number;
  isStudent: boolean;
}

타입과 인터페이스는 비슷한 기능을 하지만 몇 가지 차이점이 있음

  1. Type은 Union 타입과 Tuple 타입을 정의할 수 있지만, Interface는 그렇지 않음
type MyType = string | number;
type MyTupleType = [string, number];

interface MyInterface {
  name: string;
  age: number;
}
// 불가능
// interface MyInterface2 {
//   name: string | number;
//   age: [string, number];
// }
  1. Interface는 extends를 사용하여 상속할 수 있지만, Type은 상속을 위해서는 & 을 사용해야됨
interface Person {
  name: string;
  age: number;
}

interface Student extends Person {
  studentId: string;
}
type Person = {
  name: string;
  age: number;
};

type Student = Person & {
  studentId: string;
};

3.Type은 새로운 이름으로 기존 타입을 정의하거나, 복잡한 타입을 다룰 때 주로 사용. 반면 Interface는 객체의 구조를 정의하거나, 클래스나 함수의 타입을 정의할 때 주로 사용.


profile
TIL(거의 일기)위주. 공부한 것들은 정리해서 깃허브에 올리고 있습니다. 개인적으로 공부 중인 내용들이기 때문에 틀린 정보가 있을 수 있습니다.

0개의 댓글