简体   繁体   English

与打字稿中的“选择”相反

[英]Opposite of “Pick” in Typescript

I am trying to compose a type, which, unlike Pick , would remove certain properties from the object type. 我正在尝试组合一个类型,与Pick不同,它会从对象类型中删除某些属性。

It should work this way: 它应该这样工作:

type ObjectType = { 
    key1: number, 
    key2: string, 
    key3: boolean, 
    key4: number[] 
}

let obj: Remove<ObjectType, 'key2' | 'key4'>

Here obj 's type should be: { key1: number, key3: boolean } 这里obj的类型应该是:{key1:number,key3:boolean}

If we need to remove properties key2 and key4 , this will work: 如果我们需要删除属性key2key4 ,这将起作用:

type Without<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

let obj: Without<ObjectType, 'key2' | 'key4'>

Elaboration: 阐述:

Exclude<keyof T, K> returns 'key1' | 'key3' Exclude<keyof T, K>返回'key1' | 'key3' 'key1' | 'key3'

Pick<T, Exclude<keyof T, K>> returns the desired result { key1: number, key3: boolean } Pick<T, Exclude<keyof T, K>>返回所需的结果{ key1: number, key3: boolean }

As of TypeScript 3.5, there is an Omit helper that works as you describe. 从TypeScript 3.5开始,有一个Omit助手可以按照您的描述工作。

type ObjectType = { 
    key1: number, 
    key2: string, 
    key3: boolean, 
    key4: number[] 
}

let obj: Omit<ObjectType, 'key2' | 'key4'> // type is { key1: number, key3: boolean }

For older versions of TypeScript (>2.8), you can use a combination of Pick and Exclude as mentioned by Eduard in his answer. 对于旧版本的TypeScript(> 2.8),您可以使用Eduard在其答案中提到的PickExclude的组合。

I often make a helper type to make things a bit less verbose (note this is the exact definition used in TS 3.5) 我经常做一个帮助器类型,使事情变得不那么冗长(注意这是TS 3.5中使用的确切定义)

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

You can use 'utility-types' Omit generic. 您可以使用'utility-types'忽略泛型。

import { Omit } from "utility-types"

interface IHouse {
    rooms: number 
    gardenSize: number
    toilets: number
}

type Appartment = Omit<IHouse, "gardenSize">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM