Home > Back-end >  Implement interface inside interface dynamically TS
Implement interface inside interface dynamically TS

Time:05-05

I have this typescript interface, that works as a common structure for api calls in my react app.

export interface ICommonApiState {
    loading: boolean;
    data: any;
    serverError: string;
}

As you can see, data type is any, but i want that type to be dynamic, because, i'm going to use this same interface in multiple places, but i don't want to create a new interface every time i use it, so, how can i pase a type to data depending on what i need ?

For example, if i'm making an api call to this server that will give me an array of user names, how can i pass that type to data using same interface ? Like..


const [userNames, setUserNames] = useState<ICommonApiState<IUserNames>>(
{
 loading: false,
 serverError: '',
 data: [] -> **This receives inferred types from IUserNames**
}
)

CodePudding user response:

One solution is to make it generic like below:

export interface ICommonApiState<T> {
    loading: boolean;
    data: T;
    serverError: string;
}

That way you are controlling what gets inferred in individual components that you are using.

You already have that example usage in your code: ICommonApiState<IUserNames>

  • Related