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?

type-challenges解いてみた 初級 4-Pick編

Last updated at Posted at 2025-02-16

問題

組み込みの型ユーティリティPick<T, K>を使用せず、TからKのプロパティを抽出する型を実装します。

例えば:

  interface Todo {
    title: string
    description: string
    completed: boolean
  }

  type TodoPreview = MyPick<Todo, 'title' | 'completed'>

  const todo: TodoPreview = {
      title: 'Clean room',
      completed: false,
  }
  

ユーティリティ関数Pickを実装せよという問題です。
回答は以下です


回答

type MyPick<T, K extends keyof T> = {
  [key in K]:T[key] 
}

簡単に解説をします。

  • K extends keyof T
    extendsは「型引数に制約をつける」ものです。

つまり、ここではKkeyof Tであると型システムに知らせている形になります。
これによって、後続のkey in KT[key]がエラーとならずにすみます。

  • [key in K]
    inはここではMapped Typesとして使用されます。
    K(=keyof T)を反復している感じですね

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?