以下の内容はhttps://uga-box.hatenablog.com/entry/2024/12/16/000000より取得しました。


【Typescript】`as const`と`satisfies`の併用

TypeScriptのas constsatisfiesはそれぞれ異なる機能を持つが、併用するとどういうメリットがあるのか調べた

まずそれぞれの機能について

as const

as constリテラル型推論を強化するために使用される

通常のリテラル値は広い型(例えばstringnumber)に推論されるが、as constを使うと「リテラル型」として固定される

例えば

const example = {
  name: "John",
  age: 30,
} as const;

// 推論結果
// const example: {
//   readonly name: "John";
//   readonly age: 30;
// }

as constを使うとすべてのプロパティがリードオンリーになり、値自体も変更不可になる

satisfies

satisfiesはTypeScript 4.9以降で利用可能な構文で、指定された型に完全に一致するようにすることができる

つまり、余計なプロパティが含まれているとエラーになる

例えば

type Person = {
  name: string;
  age: number;
};

const person = {
  name: "Alice",
  age: 25,
  address: "Wonderland",
} satisfies Person;

Personに必要なプロパティ(nameage)が存在することを確認

ただし、型チェックの対象外であるプロパティ(address)でエラーになる

as constsatisfiesの併用

併用することで、リテラル型の制約と型チェックの両方を活用できる

例えば

type ButtonConfig = {
  size: "small" | "medium" | "large";
  color: "red" | "blue" | "green";
};

const config = {
  size: "small",
  color: "red",
} as const satisfies ButtonConfig;

// 推論結果
// const config: {
//   readonly size: "small";
//   readonly color: "red";
// }

これによりas constリテラル型("small""red")として固定しつつ、satisfiesにより、型ButtonConfigに一致するかどうかをチェックすることができる




以上の内容はhttps://uga-box.hatenablog.com/entry/2024/12/16/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14