Using Type Script Correctly in Server Action
Answered
Chinese Alligator posted this in #help-forum
Chinese AlligatorOP
I have a situation where i'm calling an external api from the server action, now what's an appropriate ways and practices to correctly type things there, any recommendation or suggestion/
Answered by B33fb0n3
yes, you can type it beforehand, but keep in mind, that types never validate any data. So if you need to make sure, that you get a correct response, validate your data. You can do that for example with zod. And you can also get the types directly from your zod schema if needed
6 Replies
@Chinese Alligator I have a situation where i'm calling an external api from the server action, now what's an appropriate ways and practices to correctly type things there, any recommendation or suggestion/
you can asign a type for different variables. Like that you can type your response and can work after that with it. Here's an example:
const response = await fetch(`https://api.geoapify.com/...?...`, {
method: 'GET',
}); // your api call
const result: GeoapifyResponse = await response.json(); // your typed result
const filteredData = result.features.filter(...) // work with your resultChinese AlligatorOP
but is it okay to type it before validating, it can happen that api is giving a different response
@Chinese Alligator but is it okay to type it before validating, it can happen that api is giving a different response
yes, you can type it beforehand, but keep in mind, that types never validate any data. So if you need to make sure, that you get a correct response, validate your data. You can do that for example with zod. And you can also get the types directly from your zod schema if needed
Answer
@B33fb0n3 yes, you can type it beforehand, but keep in mind, that types never validate any data. So if you need to make sure, that you get a correct response, validate your data. You can do that for example with zod. And you can also get the types directly from your zod schema if needed
Chinese AlligatorOP
yup this is the solution with which i'm working with for now, ok
cool
happy to help