1

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**
}
)

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, i'll give it a try, it seems quite basic, but i just didn't know how to do it );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.