Typescript: Omit property from a generic interface
Asked Answered
S

1

6

I am trying to create an interface that omits a property from the given type. To do so, I used Omit which results in Type so it is wrong by its definition. However, if it was not a generic interface it worked perfectly.

Consider the following sample.

interface IBaseType {
  prop1: number;
  prop2: string;
  match: boolean;
}

interface OmitMatchNoGeneric extends Omit<IBaseType, "match"> {}

interface OmitMatch<T extends { match: any }> extends Omit<T, "match"> {}

function test(genericArg: OmitMatch<IBaseType>, nonGenericArg: OmitMatchNoGeneric) {
  nonGenericArg.prop1 = 5; // the properties are suggested
  genericArg.prop1 = 5; // intelliSense fails to list the properties
}

In this example, the intelliSense of VSCode shows the list of properties for the non-generic argument but it fails to do it for the generic one. The generic argument is being treated as an object of type any.

My main concern is that if I should not use Omit what else can I use? And If I wanted to implement it with types rather than interfaces how could I do that?

Slaton answered 8/3, 2020 at 11:26 Comment(0)
M
12

TypeScript gives you an error on your generic interface:

An interface can only extend an object type or intersection of object types with statically known members.

That's why it doesn't work. (See the error on the playground.)

You can use a type instead:

type OmitMatch<T extends { match: any }> = Omit<T, "match">;

That works correctly. (On the playground.)

Mandeville answered 8/3, 2020 at 11:38 Comment(1)
This is a good exampleChymotrypsin

© 2022 - 2024 — McMap. All rights reserved.