Posts > TS Basic: Typing Promises and Async Request

TS Basic: Typing Promises and Async Request

What if our data is coming from an API? How do we make sure we have type-safe on our async function?

export const fetchData = async () => {
	const data = await fetch("our api url").then((res) => {
		return res.json()
	})
	return data
}

Here’s a example of an async function that fetching simple data and returning it to the client as json.

interface MyData {
	first_name: string,
	last_name: string,
	birth_date: number,
	age: number,
}

Let us say we already know what properties we wanted from our API.

Already Typescript will suggest ( if we hover ) to use Promise<> as we make it our function async

export const fetchData = async (): Promise<MyData> => {
	const data = await fetch("our api url").then((res) => {
		return res.json()
	})
	return data
}

You can also do this

export const fetchData = async () => {
	const data: MyData = await fetch("our api url").then((res) => {
		return res.json()
	})
	return data
}

We assign the typescript interface to the data itself.

Or you can also do

export const fetchData = async () => {
	const data = await fetch("our api url").then((res) => {
		return res.json()
	})
	return data as MyData
}

This one is called casting this is the best way to use if we don’t really know what result in our API when we fetch is going to be.

But casting allows us to make anyone become a MyData.

const owa = {} as MyData

comparing to

const owa: MyData = {}

this would give us errors because the object doesn’t include the appropriate properties.

👌Generally speaking, assigning syntax : is safer than the as syntax, and is probably what you should do in most cases.

Tags 🏷