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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With