Issue
Is there a way to declare a method overload with an optional parameter if a class generic is of a certain type? In the below example the goal is to have a class whose run method requires an argument only if the class's generic T is a number. What I've written doesn't work: I think the T in the run declaration is interpreted as a different generic than Test's generic T. Is there a way to accomplish this?
class Test<T extends string | number> {
run<T extends number>(a: number): void
run<T extends string>(a?: number): void
run(a: number): void {
console.log(a)
}
}
const a = new Test<number>();
a.run() // This should be an error, as a's generic is a number and thus its run method should require an argument.
const b = new Test<string>();
b.run() // OK, since b's generic is a string.
Solution
A conditionally-typed rest parameter is a useful choice for your method in this case:
class Test <T extends string | number> {
run (...args: T extends number ? [a: number] : [a?: number]): void {
const [a] = args;
console.log(a); // number | undefined
}
}
const a = new Test<number>();
a.run(42); // ok
a.run(); /*
^^^^^
Expected 1 arguments, but got 0.(2554) */
const b = new Test<string>();
b.run(42); // ok
b.run(); // ok
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.