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

Type alias to remove in array property

I use a 3rd party type that defines an array with specific shape like type:

type ThirdPartyType = {
    a : string;
    b : string;
    c : string;
}[];

Note this is an array type of something thas has no type alias. Since it came from an external lib, I can’t change it.

In my code, I’d like an array of items with the exact same shape, but without a specific property.

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

Let’s say I want to remove the A field, I’d like to end up with something similar to :

type WithoutA = {
    b : string;
    c : string;
}[];

But because the 3rd party actually contains a lot of fields, and is subject to change, I’d like to "remove" a field instead of "manually redeclaring" all others.

If I’ve had a type, I may have use the Omit utility type, but I have no such item‘s type.

How can I do that ?

I tried this way :

// From lib. can't change
type ThirdPartyType = {
    a : string;
    b : string;
    c : string;
}[];

// in my code
type ItemWithA =  { a : string };
type WithoutA <TItem extends ItemWithA[] > = Omit<TItem, 'a'>[];

const data : WithoutA<ThirdPartyType> = [
    {
        b : "foo",
        c : "bar"
    }
]

but the Omit applies to the array itself, not the inner type

>Solution :

You can refer to the inner element type of a given array type using indexed access types.

type ThirdPartyTypeItem = ThirdPartyType[number]

So to get the type of the array without the element property 'a', it would be:

Omit<ThirdPartyType[number], 'a'>[]

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