简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM