0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Typescriptのkeyや型を定義・使用する時に便利な構文(Type Operatorなど)

Last updated at Posted at 2022-08-22

実装しててたまに便利に使えている構文の正しい名前と公式ドキュメントのセット。ほぼ個人メモ。

Spread syntax (...)

Array/Objectにて列挙してくれる。javascriptの範囲。

type InstantNoodle = {
  productName: string;
  companyName: string;
  price: number;
}

type CapNoodle = InstantNoodle & {
  flavor: string;
}
const makeCapNoodle = (variables: { noodle: InstantNoodle, flavor: string }): CapNoodle => {
  const { noodle, flavor } = variables;
  return {
    ...noodle,
    flavor
  }
}

Keyof Type Operator

Objectのkeyを取ってきてくれる。typescriptの範囲。

type InstantNoodle = {
  productName: string;
  companyName: string;
  price: number;
}
type CapNoodle = InstantNoodle & {
  flavor: string;
}

// 'productName' | 'companyName' | 'price' | 'flavor' 
type CapNoodleKeys = keyof CapNoodle

Indexed Access Types

nestされた型の中を掘り出すのに有効。typescriptの範囲。

type InstantNoodle = {
  productName: string;
  companyName: string;
  price: number;
}

type InstantNoodleSet = {
  noodleSet: InstantNoodle[]
  discountPrice: number
}

// instantNoodleSet.noodleSet[0]と同じ=InstantNoodle
type NoodleInfo = InstantNoodleSet['noodleSet'][0]

これだけだと「え? InstantNoodle使えば良くない?」となるがcodegenなどのType自動生成を使って開発してると役に立ったりする。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?