TypeScript 接口(interface)模板

标签 typescript types interface code-cleanup

我不太确定使用 TypeScript 的正确术语。但我觉得我在重复自己,并且希望更好地模板化我的界面,这样就不那么困惑了。

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

这是我的文件:

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 中实现吗?

谢谢!

最佳答案

是的,就是这样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>>

关于TypeScript 接口(interface)模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571922/

相关文章:

Java 接口(interface)和返回类型

node.js - npm 安装@types/.../node_modules/react

typescript - TypeScript 中的 WebView 扩展

postgresql - 将单独的年、月、日、小时、分钟和秒列集成为单个时间戳列

class - 为什么一个类可以实现多个接口(interface)?

java - 为什么可以将变量赋值给接口(interface)类型?

javascript - 如何避免在React功能组件中不必要地重新渲染 "static components"?

javascript - 如何使用json_to_sheet提取xlxs中的json数据

.net - 模拟框架(在 .Net 中)如何创建模拟对象?

javascript - 如何区分对象文字和其他 Javascript 对象?