TypeScript接口模板

问题描述 投票:2回答:1

我不太确定使用TypeScript的正确术语。但我觉得我正在重复自己,并希望更好地模拟我的界面,以免减少混乱。

我有一个type,它基本上是一个潜在的字符串列表。然后我在我的interface的键中使用了这些字符串。

这是我的档案:

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
}

我想得到这样的东西:

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
}

在TypeScript中可以实现这样的事情吗?

谢谢!

typescript types interface code-cleanup
1个回答
2
投票

是的,这就是mapped types的用途

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

获得相同类型的另一种方法是使用内置的Partial和Record类型的组合:

 error: Partial<Record<PRODUCT_ACTION_KEYS, IErrorResponse>>
© www.soinside.com 2019 - 2024. All rights reserved.