Typescript: Add Omit<T,K> and Diff<T,U> to lib.d.ts

Created on 30 Oct 2017  路  9Comments  路  Source: microsoft/TypeScript



As spread and rest types is taking time I usually have to copy these types in projects. They solve the primary use case for spread/rest types and works today. I think they should fit right in next to Pick and Partial.
And even when (if?) spread and rest types is merged these would still arguably have some value.

export type Diff<T extends string, U extends string> = ({[P in T]: P} &
  {[P in U]: never} & {[x: string]: never})[T]
export type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>
Fixed Suggestion

Most helpful comment

As i noted in the Required one, i think we need a type operator here instead.

All 9 comments

Awesome type operators... even if it doesn't get included thanks for the ideas.

Oh, maybe I should have made it clear. These are not mine, I found them buried deep in a conversation once but I managed to find them again here: https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458

It also have this great type which I had totally forgotten as it's hard to find that specific comment via Google.

type Overwrite<T, U> = { [P in Diff<keyof T, keyof U>]: T[P] } & U;

Please also Required type from discussion of #15012

As i noted in the Required one, i think we need a type operator here instead.

@mhegazy Without any doubt it will be a great solution, but if it won't go in the foreseen TS version, then Required can be a nice workaround meanwhile.

See #21316.

@ahejlsberg Conditional types would be awesome and solve many problems but this issue is just about integrating types already writeable (and already written in many @types/ packages) in a default .lib.d.ts.

@Pajn Understood. The link was merely to point out there's now a better way to implement these types.

Ah, yes that's possible. I just wanted to be clear that I don't think this issue should be closed by #21316. I don't want to sound negative though, I'm super excited by conditional types in itself!

Was this page helpful?
0 / 5 - 0 ratings