LoginSignup
1
0

More than 1 year has passed since last update.

TypeScript(4.9 beta)新機能【satisfies】

Last updated at Posted at 2022-10-12

はじめに

だいぶキャッチアップが遅れてしまいましたが、先日TypeScriptの4.9(beta)がリリースされました。

非常に便利な機能が追加されているので、備忘も兼ねてご紹介します。

概要

satisfiesは、下記の2つを同時に実現するための機能です。

  1. プロパティの誤植(typo)を防ぐために型を指定したい
  2. 推論を具体的に表示してほしい

greetingsというオブジェクトを例に説明します。

const greetings = {
    hello: 'こんにちは',
    bye: 'さようなら'
}

新しく挨拶を追加する際、型を指定しないとtypoや想定外の値を入れてしまう危険性があります。

const greetings = {
    hello: 'こんにちは',
    bye: 'さようなら',
    goodMorning: 12345     // number型の値が入力
}

こういったことを防ぐために型を指定します。

今回はRecord<string, string>を追加することでプロパティと値にstringのみ許容します。

const greetings: Record<string, string> = {
    hello: 'こんにちは',
    bye: 'さようなら',
    goodMorning: 12345     // Type 'number' is not assignable to type 'string'.
}

これで型を縛ることはできましたが、こうすると推論が効かなくなってしまいます。。

const greetings: Record<string, string> = {
    hello: 'こんにちは',
    bye: 'さようなら',
    goodMorning: 'おはようございます' 
}

const helloGreeting = greetings.        // 推論が表示されない。。。

※推論(これが表示されない)
スクリーンショット (1).png

ここで satisfies の出番です。

const greetings = {
    hello: 'こんにちは',
    bye: 'さようなら',
    goodMorning: 'おはようございます' 
} satisfies Record<string, string>      // ここにsatisfiesと型を指定

こうすることで、型の制御と推論を両立させることが可能になりました。

const greetings = {
    hello: 'こんにちは',
    bye: 'さようなら',
    goodMorning: 'おはようございます' 
    notGreeting: 12345                  // Type 'number' is not assignable to type 'string'.
} satisfies Record<string, string>      // ここにsatisfiesと型を指定
const greetings = {
    hello: 'こんにちは',
    bye: 'さようなら',
    goodMorning: 'おはようございます' 
} satisfies Record<string, string>

const helloGreeting = greetings.

推論の表示
スクリーンショット (1).png

終わりに

少し前のプロジェクトで丁度この問題に直面していたので、正式にリリースされたら実際に使っていこうと思います。

最後まで読んでくださりありがとうございました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0