cosmos
Cosmos
search
blog Hello comment
{ "articleTitle": "实现Omit", "date": "2022-10-7 2:21:6", "tags": [ "typescript", "omit" ], "categories": "ts", "timestamp": 1665109266000, "readingTime": 0, "outline": " 实现Omit```tsinterface Todo { title: string descr" }
readingTime: <1min

实现Omit

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

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

const todo: TodoPreview = {
  completed: false,
}

answer

Exclude/Extract

作用:Exclude 取差集,而 Extract 取交集

注意Exclude是操作联合类型的,而Omit是操作键值对的

type Exclude<T, U> = T extends U ? never : T;

type A = Exclude<'x' | 'a', 'x'> // A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'> // A = 'a'

// 与 Exclude 实现刚好相反,Exclude 取差集,而 Extract 取交集
type Extract<T, U> = T extends U ? T : never;

// 相当于: type A = 'x'
type A = Extract<'x' | 'a', 'x'>
Edit on Github