Home > other >  How to remove keys of type `never`?
How to remove keys of type `never`?

Time:03-14

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

CodePudding user response:

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]
}
  • Related