Home > OS >  Type alias to remove in array property
Type alias to remove in array property

Time:09-20

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.

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

CodePudding user response:

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'>[]

  • Related