I have these below types declaried,
import { ReadonlyDeep } from 'type-fest';
import { AsyncFunction } from 'type-fest/source/async-return-type';
// We don't allow null. undefined is required instead.
export type SimpleArgs = (string | number | boolean | undefined)[];
export type BasicAsyncFunc<U extends SimpleArgs, R> = (...args: U) => Promise<ReadonlyDeep<R>>;
interface Memoized<U extends SimpleArgs, R> extends BasicAsyncFunc<U, R> {
cache_size: () => number;
clear_cache: () => void;
}
const memoize_async = <R, U extends SimpleArgs>(
options: { ttl: number; size: number },
f: BasicAsyncFunc<U, R>,
): Memoized<U, R> => {
return () => {
// some more logic
return f(arg) // error is here
}
}
Argument of type '[string]' is not assignable to parameter of type 'U'. '[string]' is assignable to the constraint of type 'U', but 'U' could be instantiated with a different subtype of constraint '(string | number | boolean | undefined)[]'.
Also, please can anyone explain the type declared above?
What is the signature of f
from the above type?
Also, the signature of memoize_async
?
I have a basic understanding of generics. I am confused here.
I tried as bellow,
export type SimpleArgs = (string | number | boolean | undefined)[];
SimpleArgs
should be an array of string or number or boolean and undefined is also allowed. export type BasicAsyncFunc<U extends SimpleArgs, R> = (...args: U) => Promise<ReadonlyDeep<R>>;
BasicAsyncFunc
type accepts two generics:
SimpleArgs
What U can be here? R
here? interface Memoized<U extends SimpleArgs, R> extends BasicAsyncFunc<U, R> { cache_size: () => number; clear_cache: () => void; }
No idea at all here:(
My best answer is that U
in memoized_async
is not actually (string | number | boolean | undefined)[]
.
If I did this:
const foo = memoize_async<void,number[]>({ttl:0,size:0},async ()=>{
})
arg
, which is apparently a string, would be invalid because the function expects a number. I'm not exactly sure what you would need to do as a quick fix but if I were you I would just slap a bunch of @ts-ignore's or type assertions to fix the job.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.