TypeScript 接口模板
TypeScript Interface Templating
我不太确定使用 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 中可以实现这样的功能吗?
谢谢!
是的,这就是 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
}
获得相同类型的另一种方法是使用内置的部分和记录类型的组合:
error: Partial<Record<PRODUCT_ACTION_KEYS, IErrorResponse>>
我不太确定使用 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 中可以实现这样的功能吗?
谢谢!
是的,这就是 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
}
获得相同类型的另一种方法是使用内置的部分和记录类型的组合:
error: Partial<Record<PRODUCT_ACTION_KEYS, IErrorResponse>>