[TS] Syntax | 07. keyof & typeof

2024. 7. 10. 20:35·Language/TypeScript

keyof는 딕셔너리 형태로 선언되어 있는 객체의 key값을 반환하는 키워드입니다.

이를 이용하면 interface 타입과 같이 여러 타입으로 구성되어 있는 타입의 각 요소들을 쉽게 사용할 수 있습니다.

interface Character {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

// 다음과 같은 코드를
type characterProperty = 'id' | 'name' | 'hp' | 'mp';

// keyof를 사용해서 간단하게 나타낼 수 있습니다.
type characterProperty = keyof Character;

typeof는 대상 변수의 타입을 반환하는 키워드입니다.

JS의 typeof는 타입을 문자열로 반환하지만, TS의 typeof는 타입 자체를 반환한다는 차이가 있습니다.

const redMage: Character = {
  id: '001',
  name: 'mage',
  hp: 100,
  mp: 50,
};

// redMage의 타입인 Character를 받아옵니다.
const blueMage: typeof redMage;

보통 특정 객체의 하위값들을 모두 불러올 때 이 keyof와 typeof를 같이 쓰는 경우가 많습니다.

// redMage의 타입인 Character에서 key 값인 id | name | price | membersOnly를 가져옵니다.
type mageType = keyof typeof redMage;

 

단, typeof는 배열이나 null 등의 특별한 타입은 표현할 수 없습니다.

배열의 경우 Array.isArray( )를 사용하며, null은 단순한 비교연산으로 처리할 수 있습니다.

const A = [1, 2, 3];
console.log(Array.isArray(A)); // true

console.log(A === null); // false

 

제일 일반적인 범위에서는 instanceof( ) 를 사용합니다.

class Chair {}
const test = new Chair();

console.log(test instanceof Chair); // true
728x90

'Language > TypeScript' 카테고리의 다른 글

[TS] outDir & rootDir  (0) 2024.07.11
[TS] Type | 03. Record  (0) 2024.07.10
[TS] Syntax | 06. Union & Intersection  (0) 2024.06.28
[TS] Syntax | 05. 타입 별칭(Type Alias)  (0) 2024.06.28
[TS] Type | 02. Literal 타입  (0) 2024.06.28
'Language/TypeScript' 카테고리의 다른 글
  • [TS] outDir & rootDir
  • [TS] Type | 03. Record
  • [TS] Syntax | 06. Union & Intersection
  • [TS] Syntax | 05. 타입 별칭(Type Alias)
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (276)
      • CS (40)
        • CV (2)
        • PS (34)
      • Reveiw (18)
        • Paper (18)
        • Github (0)
      • ML (8)
        • Pytorch (5)
      • Language (59)
        • Python (8)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (77)
        • React (8)
        • ReactNative (6)
        • SolidJS (20)
        • CSS (12)
      • Backend (44)
        • DB (18)
        • Node.js (11)
      • UI (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    SOLID
    deploy
    Git
    review
    ps
    frontend
    postgresql
    js
    PyTorch
    figma
    Three
    GAN
    CV
    modal
    CS
    Express
    ML
    mongo
    backend
    CSS
    ts
    API
    vscode
    python
    nodejs
    DB
    expo
    react
    ReactNative
    PRISMA
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[TS] Syntax | 07. keyof & typeof
상단으로

티스토리툴바