A
arktype•5w ago
Sealleci

How to properly infer the return type of a generic function returning ArkType schemas?

Sorry for bringing up another question about generic return types. However, I encountered this situation in project, and I really don't want to use the keyword as. Here's the link to the relevant example code: TS Playground
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
3 Replies
ssalbdivad
ssalbdivad•5w ago
It is not possible to define many generic function implementations without as or overloads, but may be possible in this with the new narrowing in TS 5.8. You could also ask this in the TS Discord since there inference you want is not specific to ArkType.
Sealleci
SealleciOP•5w ago
Yes, when I saw the changelog for version 5.8 today, I was extremely excited, as if this update was tailor-made for me (of course, that's just a joke 😉 And that's my workaround now:
interface ResponseMap {
'A': AResponse | null
'B': BResponse | null
'C': CResponse | null
}
async function myFetch<T extends QueryType>(queryType: T): Promise<ResponseMap[T]> {
...
switch(queryType){
case 'A': {
const parsedJson = arkType('string.json.parse').to(
queryModule.aResponse
)(rawJson)

if (!(parsedJson instanceof arkType.errors)) {
return parsedJson
}

break
}
case 'B': {...}
case 'C': {...}
default:
break
}
return null
}
interface ResponseMap {
'A': AResponse | null
'B': BResponse | null
'C': CResponse | null
}
async function myFetch<T extends QueryType>(queryType: T): Promise<ResponseMap[T]> {
...
switch(queryType){
case 'A': {
const parsedJson = arkType('string.json.parse').to(
queryModule.aResponse
)(rawJson)

if (!(parsedJson instanceof arkType.errors)) {
return parsedJson
}

break
}
case 'B': {...}
case 'C': {...}
default:
break
}
return null
}
Sealleci
SealleciOP•5w ago
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.

Did you find this page helpful?