【发布时间】:2021-08-06 19:26:06
【问题描述】:
我是打字稿的新手,我正在尝试制作一种具有另一种类型的类型:例如,我想做出如下的基本响应:
type Response = {
data: 'type of (any) ---> I want this to have a set type of a type or class I' create,
errors: null,
loading: false
}
然后我希望能够在类似的变量上使用上面的内容
const ordersResponse: Response<IOrder> = {
loading: false,
errors: null,
data: 'should be an array of entities that follow the IOrder type or interface'
}
有没有办法在打字稿中做到这一点?
【问题讨论】:
-
创建一个定义props类型的类或接口,见docs
-
data是否总是某个数组? -
不@Thomas 并非总是如此
-
那么最好将
data的类型定义为数组类型:Response<IOrder[]>。因为否则您需要将data的类型定义为T | T[](如当前答案所示),这是不必要的歧义。只需使用type Response<T> = { data: T; etc. }
标签: javascript node.js typescript types