#-

18 messages · Page 1 of 1 (latest)

dire bramble
#

the only way to safely type check an API response is at runtime because an API can return whatever it wants as a response at any time without your program knowing, and given that typescript only checks types at compile time, the proper solution to this is to use a runtime type checker like zod. so using zod you would create a schema for the kind of object you expect, and at runtime zod would then check that the data it received matches the schema you provided it

digital parcelBOT
#
littlelily#0

Preview:```ts
import { z } from "zod"

const emailSchema = z.string()

const email = emailSchema.parse(await fetch("/api/email").then(res => res.json()))
// ^?
// email is now correctly typed as a string, and the above line will throw an error if the run-time parsing fails
...```

dire bramble
#

if you dont care about it being safe, the only other option is to just cast the return type to the type you want
const email = (await fetch("/api/email").then(res => res.json())) as MyResponseType

digital parcelBOT
#
littlelily#0

Preview:```ts
import {NextResponse} from "next/server"

export function GET() {
return NextResponse.json({
email: "example@email.com",
})
}

export type EmailResponse = ReturnType<typeof GET>

const email = (await fetch("/api/email").then(res =>
res.json()
)) as EmailResponse
...```

dire bramble
#

ah right you need to unwrap it from the NextResponse as well

#

gimme a sec

digital parcelBOT
#
littlelily#0

Preview:```ts
import {NextResponse} from "next/server"

export function GET() {
return NextResponse.json({
email: "example@email.com",
})
}

export type EmailResponse = ReturnType<
typeof GET

extends NextResponse<infer T>
? T
: never

const email = (await fetch("/api/email").then(res =>
res.json()
)) as EmailResponse
...```

dire bramble
#

probably a better way to do it, but that's what I came up with anyway

unkempt wagon
#

I think this is probably the most straightforward solution for your case. If you are looking for better typing without having to unpack and cast things, I'd look into something like tRPC. That does add a lot of scope though and may not make sense for your project

#

Are you getting this error in your project or on the Typescript playground?

#

I don't think so. Can you paste the line(s) where you're fetching data from this endpoint?

unkempt wagon
#

Oh, that's odd. Is there a code path in your GET function that doesn't return anything?

#

Oh

#
export type Response = Awaited<ReturnType<typeof GET>> extends NextResponse<infer T> ? T : never
#

Your method is async so you need an Awaited to unwrap the Promise

#

Alternatively, you could write it like this

export type Response = ReturnType<typeof GET> extends Promise<NextResponse<infer T>> ? Promise<T> : never
#

The first one may work better depending on how you fetch the data, but the result is the same

winged moon