I have the following interfaces
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,
}
}
so now my generic type is implement dynamically the ApiResponse T
.
But i have more nested structure for example when i git my API i get
{
count: 1,
response: {
id: '1',
isTheUserAdmin: true,
data: {
linkTypes: string[],
folderTypesIds: number[]
}
}
}
so when i create my first generic type generic = CollectionResponse<ApiResponse>;
i need to pass another generic for my data
property that is actually inside my response generic
so i will have this interface
interface Data {
linkTypes: string[],
folderTypesIds: number[]
}
how can i include that in ApiReponse on the fly so at the end i will get type check for data also
that is inside the response
property
CodePudding user response:
What you are describing is a generic ApiResponse
.
interface ApiResponse<T> {
id: string;
isTheUserAdmin: boolean;
data: T;
}
Now you can do:
const myApiResponse = ApiResponse<{ hello: boolean }> {
id: '1',
isTheUserAdmin: true,
data: {
hello: true
}
}
Now your Generic
type needs to also be generic in order to pass that type through.
type Generic<T> = CollectionResponse<ApiResponse<T>>;
Now you pass your api response data type to that and it will end up in the right place.
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],
}
}
}