filmov
tv
Modify TypeScript generic function parameters and return types [duplicate]

Показать описание
Below, you can find the text related to the question/problem. In the video, the question will be presented first, followed by the answers. If the video moves too fast, feel free to pause and review the answers. If you need more detailed information, you can find the necessary sources and links at the bottom of this description. I hope this video has been helpful, and even if it doesn't directly solve your problem, it will guide you to the source of the solution. I'd appreciate it if you like the video and subscribe to my channel!Modify TypeScript generic function parameters and return types [duplicate]
Can I make all the arguments of a function readonly and convert that function to an async function?
For example:
declare function foo T (bar: T, baz: T[]): T;
declare function foo T (bar: T, baz: T[]): T;
Convert to
declare function foo T (bar: Readonly T , baz: readonly T[]): Promise T ;
declare function foo T (bar: Readonly T , baz: readonly T[]): Promise T ;
I've tried this, which works 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 ;
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 messes up the generic function by turning all the original generic type T into unknown.
Foo
T
unknown
P.S. Thanks for the answers.
However, is it possible to do this for all functions within an interface?
For example:
interface Methods {
foo T (bar: T, baz: T[]): T;
bar(baz: string): void;
}
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 ;
}
interface Methods {
foo T (bar: Readonly T , baz: readonly T[]): Promise T ;
bar(baz: string): Promise void ;
}
If add another type based on the above:
type MakeFunctionsAsync T = {
[functionName in keyof T]: MakeFunctionAsync T[functionName] ;
};
type MakeFunctionsAsync T = {
[functionName in keyof T]: MakeFunctionAsync T[functionName] ;
};
There doesn't seem to be a place to fill in the generic type parameter.
type MakeFunctionsAsync T, U = {
[functionName in keyof T]: MakeFunctionAsync T[functionName] U ;
};
type MakeFunctionsAsync T, U = {
[functionName in keyof T]: MakeFunctionAsync T[functionName] U ;
};
This won't work.
Tags: typescriptSource of the question:
Question and source license information: