Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove keys of type `never`?

I’ve created this utility type called Override which I find quite handy, but one thing that’s been bothering me is that it’s not very convenient to completely remove properties.

In the example below, I want Bar to retain a from Foo, override b to be a string instead of a number, and remove c. However, c sticks around, it’s just typed as never. How can I remove all the nevers intead?

type Override<A, B> = Omit<A, keyof B> & B

type Foo = {
    a: string
    b: number
    c: boolean
}

type Bar = Override<Foo, {
    b: string
    c: never
}>

function f(bar: Bar) {
   console.log(bar.c)
}

Playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Rather than & B, you can intersect with a mapping of a new object type with the never values removed.

type Override<A, B> = Omit<A, keyof B> & {
    [K in keyof B as B[K] extends never ? never : K]: B[K]
}

This can be extended to remove any sort of value you want.

type Override<A, B> = Omit<A, keyof B> & {
    [K in keyof B as B[K] extends never | void ? never : K]: B[K]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading