> For the complete documentation index, see [llms.txt](https://simian114.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://simian114.gitbook.io/blog/undefined/undefined-3/undefined/easy/06.-pick.md).

# 06. Pick

[typescript 에서 in 키워드](https://stackoverflow.com/a/50214853)

[문제](https://github.com/type-challenges/type-challenges/blob/master/questions/4-easy-pick/README.md)

[해설](https://ghaiklor.github.io/type-challenges-solutions/en/easy-pick.html)

## 문제

Implement the built-in `Pick<T, K>` generic without using it.

Constructs a type by picking the set of properties `K` from `T`.

For example:

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

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

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

## 풀이

```typescript
type MyPick<T, K> = 

// 0. K 는 T 의 키가 되어야한다. 제한을 걸자
type MyPick<T, K keyof T> = ;

// 1. 리턴타입은 객체의 형식이어야한다.
type MyPick<T, K keyof T> = {}

// 2. 리턴
type MyPick<T, K keyof T> = { [P in K]: T[P] }
```

## 추가설명

`type MyPick<T, K keyof T>` 로 제한을 걸기는 했지만, 최종적으로 스스로 문제를 해결하지는 못했다. 설명을 보자.

최종적으로 문제의 해결은 정말 간단하다. 먼저 해줘야할 건 객체형식으로 표현하기 위한 `{ }` 다. 그리고 내부에서는 **반복을 돌아야한다.** 그리고 그 반복은 `T` 의 `key` 인 `K` 다.

**\[P in K]** 라는 문법을 몰랐다. 이렇게 `[P in K]` 를 사용하게 되면 `K` 의 반복을 돌게 된다. 따라서 `{ [P in K]: T[P] }` 를 하게 되면 반복을 돌면서 우리가 원하는 `property` 만을 가지고 올 수 있게 된다.
