How to set type for async function?
- Set type for async function
async function fetchApi(path: string) { const response = await fetch(`https://example.com/api${path}`) return response.json(); } // Return type of the fetchApi function is Promise<any>
async function fetchApi<ResultType>(path: string): Promise<ResultType> { const response = await fetch(`https://example.com/api${path}`); return response.json(); } // Return type of the fetchApi function is Promise<ResultType>
- Set type when calling generic type function
const data = await fetchApi<User[]>('/users')
- If the calling code does not include the generic type,
ResultType
would be bound tounknown
const data = await fetchApi('/users')
console.log(data.a) // Error! Since the type of data is unknown, this code will not be able to access a property of the object.
- If you are not planning to add a specific type to every single call of your generic function, you can add a default type to the generic type parameter.
This can be done by adding= DefaultType
right after the generic type, like this:
async function fetchApi<ResultType = Record<string, any>>(path: string): Promise<ResultType> { const response = await fetch(`https://example.com/api${path}`); return response.json(); } // In this case, default type is Record<string, any>
const data = await fetchApi('/users') console.log(data.a) // TypeScript will recognize data as an object with keys of type string and values of type any, allowing you to access its properties.
How to allow only certain shapes to be passed into the generic type parameter?
async function fetchApi<ResultType extends Record<string, any>>(path: string): Promise<ResultType> { // ... }
extends Record<string, any>
indicates an object with keys of type string
and values of type any
. You can make your type parameter extend any valid TypeScript type.
Leave a Reply