본문 바로가기
IT/typescript

[Typescript] satisfies

by 내일은교양왕 2024. 2. 22.

배경

개발자들은 딜레마에 빠진다. 

개발 하다보면 object의 맴버들이 type에 매칭되길 원할 뿐만 아니라 타입추론으로 인하여 가장 명확한 타입을 유지하기 원한다.

 

상황 예

const palette = {
    red: [255, 0, 0],
    green: '#00ff00',
    bule: [0,0, 0]
  //^^^^ typo  
} 

const redComponent = palette.red.at(0)
const greenNormalized = palette.green.toUpperCase()

 

기존 시도

object에 type 선언했더니 로직에서 에러 발생

type Colors = 'red' | 'green' | 'blue'
type RGB = [red: number, green: number, blue: number]
const palette:Record<Colors, string | RGB> = {
    red: [255, 0, 0],
    green: '#00ff00',
    blue: [0,0, 0]
} 

const redComponent = palette.red.at(0)
console.log(redComponent)
const greenNormalized = palette.green.toUpperCase() 
//Property 'toUpperCase' does not exist on type 'string | RGB'

 

satisfies 이용한 시도

key에서 에러 발생

type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];
const palette = {
    red: [255, 0, 0],
    green: "#00ff00",
    bleu: [0, 0, 255] //  ~~~~ The typo is now caught!
} satisfies Record<Colors, string | RGB>;

// Both of these methods are still accessible!
const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();

 

value에서도 에러 발생

type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];
const palette = {
    red: [255, 0, 0],
    green: "#00ff00",
    blue: [0, 0]
//  Type '[number, number]' is not assignable to type 'RGB'.
} satisfies Record<Colors, string | RGB>;
// Both of these methods are still accessible!
const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();

 

 

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator

 

Documentation - TypeScript 4.9

TypeScript 4.9 Release Notes

www.typescriptlang.org

 

'IT > typescript' 카테고리의 다른 글

[Typescript] Parameters<Type>  (0) 2024.03.11
[Typescript] Type-Only Imports and Export  (0) 2024.03.08
[Typescript] 타입 호환성  (0) 2024.02.22
[Typescript] Branded type  (0) 2024.02.21
[Typescript] asserts를 이용한 타입 가드 활용  (0) 2024.02.05