我有以下介面
interface CollectionResponse<T> {
count: number;
response: T
}
interface ApiResponse {
id: string;
isTheUserAdmin: boolean;
}
type generic = CollectionResponse<ApiResponse>;
const obj: generic = {
count: 1,
response: {
id: '1',
isTheUserAdmin: true,
}
}
所以現在我的泛型型別是動態實作的ApiResponse T。
但是我有更多的嵌套結構,例如當我 git 我的 API 時
{
count: 1,
response: {
id: '1',
isTheUserAdmin: true,
data: {
linkTypes: string[],
folderTypesIds: number[]
}
}
}
所以當我創建我的第一個泛型時type generic = CollectionResponse<ApiResponse>;
我需要為我的data屬性傳遞另一個泛型,它實際上在我的回應泛型中
所以我會有這個界面
interface Data {
linkTypes: string[],
folderTypesIds: number[]
}
我怎樣才能將它包含在 ApiReponse 中,所以最后我將對response屬性內的資料進行型別檢查
uj5u.com熱心網友回復:
你所描述的是一個通用的ApiResponse.
interface ApiResponse<T> {
id: string;
isTheUserAdmin: boolean;
data: T;
}
現在你可以這樣做:
const myApiResponse = ApiResponse<{ hello: boolean }> {
id: '1',
isTheUserAdmin: true,
data: {
hello: true
}
}
現在您的Generic型別也需要是通用的才能傳遞該型別。
type Generic<T> = CollectionResponse<ApiResponse<T>>;
現在你將你的 api 回應資料型別傳遞給它,它最終會出現在正確的位置。
interface MyDataType {
linkTypes: string[]
folderTypesIds: number[]
}
const obj: Generic<MyDataType> = {
count: 1,
response: {
id: '1',
isTheUserAdmin: true,
data: {
linkTypes: ['a', 'b', 'c'],
folderTypesIds: [1, 2, 3],
}
}
}
看游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519894.html
標籤:打字稿仿制药
