Reputation: 7299
I have a interface which is as follow
export interface ApiState {
data: null|unknown;
error: null|AxiosError;
}
export const state: ApiState = {
data: null,
error: null
};
Later on I call a function which fills the state.
export const request = async<T>( config: AxiosRequestConfig ) => {
try {
const { data } = await http.request<T>(config);
// How can I cast the state.data to another 'type'?
state.data = data as T; // how can I make the intellisense recognize the passed <T> type?
} catch(e) {
state.error = e;
}
}
However, in another file the type of state.data
is still seen as unknown.
Here is how I call it and pass the type
import { state } from './api/api.module.ts';
export const user = async () => {
await request<ApiUser>({ url: '/api/user', method: 'GET' });
// this is seen as unknown
// How can I make this of type ApiUser?
console.log(state.data)
}
Upvotes: 1
Views: 493
Reputation: 2220
What you directly want is not possible. You try to assign a generic value to a variable of type unknown
. The only way of doing it is to return the state object and store it in a variable:
export interface ApiState<T> {
data: null|T;
error: null|AxiosError;
}
export const request = async<T>( config: AxiosRequestConfig ) => {
const state: ApiState<T> = {
data: null,
error: null
}
try {
const { data } = await http.request<T>(config);
// How can I cast the state.data to another 'type'?
state.data = data as T; // how can I make the intellisense recognize the passed <T> type?
} catch(e) {
state.error = e;
}
return state;
}
export const user = async () => {
const state = await request<ApiUser>({ url: '/api/user', method: 'GET' });
// this is seen as unknown
// How can I make this of type ApiUser?
console.log(state.data)
}
Upvotes: 3