Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typescript give type `never` when excluding extended interface

Tags:

typescript

I created a function to strip an object of an interface. However Typescript (Version 3.2.2) now claims the type is never when it should be a type with property child

interface Child extends Parent {
    child: string
}

interface Parent {
    parent: string
}

const a: Child = { child: "", parent: "" }

const b = removeParent(a);

function removeParent<T extends Parent>(obj: T) {
    delete obj.parent;
    return obj as Exclude<T, Parent>;
}

// b is now type never...

This does work:

function removeParent<T extends Parent>(obj: T) {
    delete obj.parent;
    type Without<T, K> = Pick<T, Exclude<keyof T, K>>;
    return obj as Without<T, "parent">;
}

However I want a generic solution that doesn't require me writing out the types to exclude.

like image 206
Red Riding Hood Avatar asked Feb 25 '26 01:02

Red Riding Hood


1 Answers

I think you do not want Exclude<T, Parent>

Exclude is essentially: type Exclude<T, U> = T extends U ? never : T

and as a result, your return type will return never since T extends Parent in your usage.

What I think you're really after is: Pick<T, Exclude<keyof T, keyof Parent>>

so that you're saying 'pick all properties of T that do not exist int he parent'

function removeOneAndTwo<T extends Parent>(obj: T): Pick<T, Exclude<keyof T, keyof Parent>> {
  delete obj.one;
  delete obj.two;
  return obj;
}
like image 181
Esteban Avatar answered Feb 27 '26 19:02

Esteban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!