[TypeScript] as const와 readonly

Slowly But Surely·2024년 1월 31일
  1. Array에 as const 사용
const newArr = ["A", "B", "C"] as const;
newArr.push("D"); // TypeScript error

TS는 readonly 튜플 타입으로 infer하게 됨. push(), pop()등 불가

  1. Object에 as const 사용
const config = {
  endpoint: "https://api.example.com",
  retries: 5
} as const;

// Trying to modify any property will result in a TypeScript error
config.endpoint = "https://api.newexample.com"; // TypeScript error
config.retries = 10; // TypeScript error
const config = {
  endpoint: "https://api.example.com",
  retries: 5
} as const;

// Trying to modify any property will result in a TypeScript error
config.endpoint = "https://api.newexample.com"; // TypeScript error
config.retries = 10; // TypeScript error
const userProfile = {
  name: "John Doe",
  interests: ["coding", "music", "gaming"] as const,
} as const;

userProfile.name = "Jane Doe"; // TypeScript error
userProfile.interests.push("reading"); // TypeScript error
profile
안녕하세요

0개의 댓글