0

I would like to model an interface that has array that accepts objects as long as they extend a particular interface. I'm still learning Generics, so please bear with me.

Here's my "base" interface:

export interface IEntry {
  sys: {
    contentType: {
      . . .
    }
  }
}

and my extended interface:

export interface IWorkSample extends IEntry {
  fields: {
    . . .
  }
}

Here's the interface that has the array:

export interface IEntries {
  items: IEntry[]; <- doesn't allow for IWorkSample or future interfaces
  limit: number;
  skip: number;
  sys: {
    type: string;
  };
  total: number;
}

I can of course do:

items: IWorkCategory[] | IWorkSample[];

but then I have to keep adding types.

I'd like to be able to write the IEntries interface to allow items to contain objects that extend IEntry. I'm reading the Generics Documentation, but obviously coming up short.

I can use items: any[], but that of course doesn't guarantee the objects will have properties I'll expect in the future. Can someone please help me out with an example that makes sense?

1 Answer 1

2

You can introduce a type parameter that extends IEntry like below:

interface IEntries<T extends IEntry> {
    items: T[];
    // ...
}

And use it like:

let entries: IEntries<IWorkSample> = {
    items: ... // IWorkSample[] here
}
Sign up to request clarification or add additional context in comments.

3 Comments

IEntries doesn't extend IEntry though... items is an array of types that extend IEntry...or am I completely missing the point?
Correct. That is what the example above shows as well IEntries does not extend IEntry only the type parameter T extends IEntry.
So far so good. I'm able to access the properties I expect now. Thank you!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.