Search code examples
typescriptaxios

Axios return as specific type


I'm trying to use Axios to make a get call as a specific type using TypeScript.

Axios.get<MyType>('myurl')
     .then(response => resolve(response.data))

When I hover over response it says it is being returned as AxiosResponse<MyType>, however it is just being returned as a generic object.

Am I missing anything?

It looks as though TypeScript only enforces types at compile time and not runtime. I assume this means we can't cast to type via the Axios call above. Can someone confirm this is true?


Solution

  • You are correct that there are no types at runtime when using TypeScript. Your type cast does therefore not do anything at all at runtime. This is intended by the TypeScript developers. See this GitHub issue and the TypeScript design goals.

    If you want to implement runtime type checking, there are several tools out there. I can recommend io-ts. It is very powerful, although the learning curve can be steep (especially if you have little/no background in functional programming).