简体   繁体   中英

convert interface property 'unknown' to 'type' in TypeScript

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM