Search code examples
typescriptinterfacetypescript-typingsextendstypescript-generics

Typescript: Omit property from a generic interface


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?


Solution

  • 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.)