5

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?

1 Answer 1

11

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

1
  • 1
    This is a good example
    – Iago Leão
    Oct 22, 2021 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.