A
arktype2mo ago
Cobain

Function which receives a arktype's 'type'

I'm trying to do something like this:
async rateLimitedCallApi<T>(url: string, schema: Type<T>): Promise<T> {
await this.rate_limiter.acquire();

const response = await fetch(url, this.request_data);
if (!response.ok) {
throw Error(`Invalid request: ${response}`)
}

const parsedResponse = schema(await response.json());
async rateLimitedCallApi<T>(url: string, schema: Type<T>): Promise<T> {
await this.rate_limiter.acquire();

const response = await fetch(url, this.request_data);
if (!response.ok) {
throw Error(`Invalid request: ${response}`)
}

const parsedResponse = schema(await response.json());
But the parsedResponse isn't of type T, so how do I make this function accept as schema anything created using type({...})
6 Replies
Stuart B
Stuart B2mo ago
try:
async rateLimitedCallApi<T extends Type>(url: string, schema: T)
async rateLimitedCallApi<T extends Type>(url: string, schema: T)
ssalbdivad
ssalbdivad2mo ago
What do you mean that it's not of type T? T is not constrained here. Are you just not wanting to cast the return? If that's the case it is likely a limitation of TS. It falls apart very quickly trying to do anything with generic types in a function. See my recommendation here: https://discord.com/channels/957797212103016458/1289555141355241573/1289572327511687208 This will generally work in the default scope, but use type.Any if you want it to accept all type instances
Stuart B
Stuart B2mo ago
Good to know!
Cobain
CobainOP2mo ago
async rateLimitedCallApi<T>(url: string, schema: Type<T>): Promise<T> {
await this.rate_limiter.acquire();

const response = await fetch(url, this.request_data);
if (!response.ok) {
throw Error(`Invalid request: ${response}`);
}

const json = await response.json();
const parsedResponse = schema(json);

if (parsedResponse instanceof type.errors) throw parsedResponse;

return parsedResponse as T;
}
async rateLimitedCallApi<T>(url: string, schema: Type<T>): Promise<T> {
await this.rate_limiter.acquire();

const response = await fetch(url, this.request_data);
if (!response.ok) {
throw Error(`Invalid request: ${response}`);
}

const json = await response.json();
const parsedResponse = schema(json);

if (parsedResponse instanceof type.errors) throw parsedResponse;

return parsedResponse as T;
}
So casting here is ok if I don't cast it, the parsedResponse has this type: finalizeDistillation<T, _distill<T, { endpoint: "out"; }>>
ssalbdivad
ssalbdivad2mo ago
Yeah like I said it's just a TS limitation it can't actually evaluate expressions on generic parameters You can see how there's really no unique arktype logic here so that's not something I control Because if you use the schema on its own it is inferred correctly
Cobain
CobainOP2mo ago
Yeah typescript with generic types in functions has never worked well I understand, thanks!
Want results from more Discord servers?
Add your server