2

I'm not too sure one correct terms for using TypeScript. But I feel like I'm repeating myself and would like to template my interface better so be less confusing.

I've got a type which is basically a list of potential strings. Then I've used those strings in keys for my interface.

This is my file:

import { IErrorResponse } from '~/interfaces'

export type PRODUCT_ACTION_KEYS =
  | 'creatingProducts'
  | 'fetchingCategories'
  | 'fetchingProduct'
  | 'fetchingProducts'

export interface IProductsReducer {
  categories: any[]
  error: {
    creatingProduct?: IErrorResponse
    fetchingCategories?: IErrorResponse
    fetchingProduct?: IErrorResponse
    fetchingProducts?: IErrorResponse
  }
  is: {
    creatingProduct: boolean
    fetchingCategories: boolean
    fetchingProduct: boolean
    fetchingProducts: boolean
  }
  products: any[]
  selectedProduct?: any
}

I'd like to get something like this:

import { IErrorResponse } from '~/interfaces'

export type PRODUCT_ACTION_KEYS =
  | 'creatingProducts'
  | 'fetchingCategories'
  | 'fetchingProduct'
  | 'fetchingProducts'

export interface IProductsReducer {
  categories: any[]
  error: {
    [PRODUCT_ACTION_KEYS]?: IErrorResponse
  }
  is: {
    [PRODUCT_ACTION_KEYS]: boolean
  }
  products: any[]
  selectedProduct?: any
}

Would something like this be achievable in TypeScript?

Thanks!

1 Answer 1

2

Yes that's what mapped types are for

export interface IProductsReducer {
  categories: any[]
  error: {
    [key in PRODUCT_ACTION_KEYS]?: IErrorResponse
  }
  is: {
    [key in PRODUCT_ACTION_KEYS]: boolean
  }
  products: any[]
  selectedProduct?: any
}

Another way to get the same type is to use a combination of built-in Partial and Record types:

 error: Partial<Record<PRODUCT_ACTION_KEYS, IErrorResponse>>
Sign up to request clarification or add additional context in comments.

Comments

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.