实现 Optional
作者:xie392地址:https://v.douyin.com/ieQ7ytem/更新时间:2024-12-21
案例代码
1interface Article {2title: string3content: string4author: string5date: Date6}78// 看下面 Omit 、Partial 、Pick 的例子9type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>1011type CreateArticleOptions = Optional<Article, 'author' | 'date'>1213function createArticle(options: CreateArticleOptions) { }1415createArticle({title: '11', content: ''})161718/**19* =============================================================================================20* 下面分别是 Omit 、Partial 、Pick 的例子21* =============================================================================================22*/23interface Todo {24title: string25description: string26completed: boolean27}2829/**30* Omit31* 移除某些属性,新类型中不能有这些属性32*/33// 移除两个属性 'description' | 'completed'34type TodoOmit = Omit<Todo, 'description' | 'completed'>3536const todo: TodoOmit = {37title: '1'38}3940/**41* Pick42* 挑选某些属性,新类型中必须要拥有这些属性43*/44// 挑选两个属性 'title' | 'description'45type TodoPick = Pick<Todo,'title' | 'description'>4647const todo2: TodoPick = {48title: '1',49description: ''50}5152/**53* Partial54* 部分属性类型,新类型中变为可选55*/56// 全部类型变为可选57type TodoPartial = Partial<Todo>5859const todo3: TodoPartial = {}
目录