Is it possible to make all the arguments of a function readonly and convert that function to an async function?
For instance:
declare function foo<T>(bar: T, baz: T[]): T;
Transform into
declare function foo<T>(bar: Readonly<T>, baz: readonly T[]): Promise<T>;
I attempted this approach, which worked for non-generic functions:
type ReadonlyArrayItems<T> = { [P in keyof T]: Readonly<T[P]> };
type MakeFunctionAsync<T> = (...args: ReadonlyArrayItems<Parameters<T>>) => Promise<ReturnType<T>>;
type Foo = MakeFunctionAsync<typeof foo>;
However, the new function type Foo
alters the generic function by changing all occurrences of the original generic type T
to unknown
.
P.S. Thank you for the responses.
Is it feasible to apply this to all functions within an interface?
For example:
interface Methods {
foo<T>(bar: T, baz: T[]): T;
bar(baz: string): void;
}
Become this
interface Methods {
foo<T>(bar: Readonly<T>, baz: readonly T[]): Promise<T>;
bar(baz: string): Promise<void>;
}
If another type is added based on the above:
type MakeFunctionsAsync<T> = {
[functionName in keyof T]: MakeFunctionAsync<T[functionName]>;
};
There doesn't appear to be a place to insert the generic type parameter.
type MakeFunctionsAsync<T, U> = {
[functionName in keyof T]: MakeFunctionAsync<T[functionName]<U>>;
};
This method will not work.