简体   繁体   中英

How to use enum value as interface key in Typescript

I am using a GraphQL API and trying to define the typescript types for it. I now have an enumeration stating all the publication types and i want to define the fields for each of those publication types. For this i am creating an interface where the key is the publication type and the value is the fields that belong to this publication type. To prevent duplicate strings, i want the key of the interface to use the literal PUBLICATION_TYPES enum value. However, Typescript does not checks all types correctly after i try so. The types are as follows:

enum PUBLICATION_TYPES {
  ARTICLE_SINGLE = 'Article',
  ARTICLE_LIST = 'Articles',
}

interface ArticleFields {
  title: string;
  body: string
}

interface ArticleResponse {
  [PUBLICATION_TYPES.ARTICLE_SINGLE]: ArticleFields;
}

This does compile, however it does not compile to the type i am searching. The output i am looking for is as follows:

interface ArticleResponse {
  Article: ArticleFields;
}

But this is my current output:

let i: ArticleResponse;

i[PUBLICATION_TYPES.ARTICLE_SINGLE].title; 
// This checks and autocompletes correctly.

i[PUBLICATION_TYPES.LIST].foo;
// This also passes all type checks, even though PUBLICATION_TYPES.LIST
// has not been specified as Interface key.

Could someone point me in the right direction? I am using Typescript 4.1.3. Thank you in advance.

According to Nishant 's comment I did not have strict mode enabled.

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