TypeScript挑战(九)- 实现 Omit

TypeScript Challenge - 实现 Omit<T, K>

题目


实现 Omit<T, K>

不使用 Omit 实现 TypeScript 的 Omit<T, K> 范型。

Omit 会创建一个省略 K 中字段的 T 对象。

例如:

1
2
3
4
5
6
7
8
9
10
11
interface Todo {
title: string
description: string
completed: boolean
}

type TodoPreview = MyOmit<Todo, 'description' | 'title'>

const todo: TodoPreview = {
completed: false,
}

测试用例


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Equal, Expect } from '@type-challenges/utils'

type cases = [
Expect<Equal<Expected1, MyOmit<Todo, 'description'>>>,
Expect<Equal<Expected2, MyOmit<Todo, 'description' | 'completed'>>>
]

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

interface Expected1 {
title: string
completed: boolean
}

interface Expected2 {
title: string
}

答案

1
2
3
type MyOmit<T, K> = {
[P in Exclude<keyof T,K>]: T[P]
}