[英]Typescript how do I extend an interface which uses a generic type?
I have this interface structure set up:我设置了这个接口结构:
export interface Response<T> {
hasMoreResults: boolean
pageToken: string | null
status: string
result: T
}
export interface ArrayResponse<T> {
hasMoreResults: boolean
pageToken: string | null
status: string
result: T[]
}
As there are many shared fields I want to write something like this instead:由于有很多共享字段,我想写这样的东西:
interface ArrayResponse extends Response<T>{
result: T[]
}
However this throws an error I cannot fix.但是,这会引发我无法修复的错误。 Is there a straightforward way of changing the type of the property which uses the generic in both cases?
是否有一种直接的方法来更改在这两种情况下都使用泛型的属性类型? I don't want to do
T | T[]
我不想做
T | T[]
T | T[]
as the result in one interface, as this will cause problems in my code. T | T[]
作为一个接口的结果,因为这会导致我的代码出现问题。 Thanks.谢谢。
Looking at your code the only difference between ArrayResponse
and Response
is that result
is an array.查看您的代码,
ArrayResponse
和Response
之间的唯一区别是result
是一个数组。
You could use:你可以使用:
export interface Response<T> {
hasMoreResults: boolean
pageToken: string | null
status: string
result: T
}
export type ArrayResponse<T> = Response<T[]>
As Response
can already take any type as an argument. As
Response
已经可以将任何类型作为参数。
As far as I can tell, ArrayResponse
is just an instantiation of Response
where T
is an array.据我所知,
ArrayResponse
只是Response
的一个实例,其中T
是一个数组。 If we want to define ArrayResponse
to just pass in the item type we could do this:如果我们想将
ArrayResponse
定义为只传入项目类型,我们可以这样做:
export interface Response<T> {
hasMoreResults: boolean
pageToken: string | null
status: string
result: T
}
export interface ArrayResponse<T> extends Response<T[]> {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.