Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit fields in object spread?

Tags:

typescript

I have one interface with many fields and other interface with almost all fields (just one less).

How in TypeScript without untyped unsafe crutches (<>, as, any, unknown and similar) can one exclude fields in object spread (so without enumerating every field I want to copy)?

interface A {
    fieldA: number;
    fieldB: string;
    fieldC: number;
    fieldD: string;
    fieldE: number;
    fieldF: string;
}

interface B {
    fieldA: number;
    fieldB: string;
    fieldC: number;
    fieldD: string;
    fieldE: number;
    // no fieldF here
}

const a: A = {
    fieldA: 1,
    fieldB: 'b',
    fieldC: 3,
    fieldD: 'd',
    fieldE: 5,
    fieldF: 'f'
}

const b: B = {
    ...a,
    fieldF: undefined
};

This doesn't compile, because fieldF is still present, only have a value of undefined.

like image 780
menfon Avatar asked Dec 31 '18 15:12

menfon


People also ask

How do I remove a property from the spread operator?

You simply destructure the object into two parts: one part is the property you're trying to remove ( drugName in this case), and the other part is the rest of the object, that you want to keep ( drugWithoutName in this case).

Can Spread operator be used on object?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

Does object spread overwrite?

Order matters: the object spread operator will overwrite properties that are defined before it, but not after.

Does spread operator overwrite property?

Using the spread operator to overwrite an object property It's a super clean syntax and easy to see which value we are overwriting. The only thing you must remember while using this method is that the order matters. If we, for instance, put the property we want to overwrite.


1 Answers

If you don't mind an intermediate step, you can do something like this:

const { fieldF, ...everythingExceptF } = a;
const b: B = everythingExceptF;

This combines the spread and rest operators. The compiler seemed happy with this on my machine, and it gives me the result you'd expect.

Note: this will also create the constant fieldF, which you may or may not want. If you already need that name for some other reason in the same scope, you can reassign it like this:

const { fieldF: someOtherName, ...everythingExceptF } = a;
like image 145
Mark Ormesher Avatar answered Oct 12 '22 00:10

Mark Ormesher