Chrissi Grilus
Chrissi Grilus

Reputation: 1375

Typescript narrow a type from a given interface

In the project I am working on we use GraphQL with the

 __typename: "Specific" | "Normal"

property. In this particular request I can only get an array of items with the __typename of "Specific". How do I tell Typescript that I want exactly that interface but I am sure that __typename can only have that one value.

Upvotes: 0

Views: 199

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

If I understand you correctly, you have a query that you know will only return __typename: "Specific" items and you want to type them accordingly without repeating all of the other aspects of the interface with that property.

To do that, you can define a new interface like this:

type NarrowedInterface = OriginalInterface & {
  __typename: "Specific";
};

Playground link

Upvotes: 1

Related Questions