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[]
as the result in one interface, as this will cause problems in my code. Thanks.
Looking at your code the only difference between ArrayResponse
and Response
is that result
is an array.
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.
Sure, you can omit it like this
export interface ArrayResponse<T> extends Omit<Response<T>, "result"> {
result: T[]
}
As far as I can tell, ArrayResponse
is just an instantiation of Response
where T
is an array. If we want to define ArrayResponse
to just pass in the item type we could do this:
export interface Response<T> {
hasMoreResults: boolean
pageToken: string | null
status: string
result: T
}
export interface ArrayResponse<T> extends Response<T[]> {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.