본문 바로가기
IT

TS - Record<K, T>

by 내일은교양왕 2023. 6. 27.

개념
key가 K Type으로, value에 대한 값이 T인 객체 타입
v2.1부터 도입

type Record<K extends string, number, symbol, T> = {
  [P in K]: T
}

 

Examples
문자열 리터럴 key

type names = 'chuck' | 'mary'

type family = Record<names, number>

const myFamily: family = {
  chuck: 20,
  mary: 30,
}

enum key

enum names {
  'chuck' = 1
  'mary' = 2
}

type family = Record<names, number>

const myFamily: family = {
  chuck: 20,
  mary: 30,
}


keyof key

type student = {
  name: string
  age: number
  address: string
  gpa: number
}

type studentRecordType = Record<keyof student, string>
const studentImpl: studentRecordType = {
  name: 'chuck',
  age: '30',
  address: 'younin'
  gpa: '4.0'
}

//with interface
interface student {
  name: string
  age: number
  address: string
  gpa: number
}


const studentImpl: Record<keyof student, string> = {
  name: 'chuck',
  age: '30',
  address: 'younin',
  gpa: '4.0'
}



참고
https://developer-talk.tistory.com/296