TypeScript Version: 3.5.1
Search Terms:
extends keyof narrowing
infer not narrowing type
Code
type MethodArguments<T> = [T] extends [(...args: infer U) => any]
? U
: [T] extends [void] ? [] : [T];
interface User {
setName(name: string): void;
setAge(age: number): void;
setBirthday(year: number, month: number, day: number): void;
getName(): string;
getAge(): number;
getBirthday(): { year: number, month: number, day: number };
}
class SomeClass {
constructor(public user: User) { }
handle<K extends keyof User>(method: K, ...args: MethodArguments<User[K]>): void {
let result: ReturnType<User[K]>;
switch (method) {
case "setName":
const [
name
] = args;
result = this.user.setName(name);
break;
case "setAge":
const [
age
] = args;
result = this.user.setAge(age);
break;
case "setBirthday":
const [
year,
month,
day
] = args;
result = this.user.setBirthday(year, month, day);
break;
case "getName":
result = this.user.getName();
break;
case "getAge":
result = this.user.getAge();
break;
case "getBirthday":
result = this.user.getBirthday();
break;
}
console.log(result);
}
}
Expected behavior:
In the switch case each case should narrow the type of method, args and result. However, this doesn't happen.
Actual behavior:
What's actually occurring is that in each switch case, method has the type K extends "setName" | "setAge" | "setBirthday" | "getName" | "getAge" | "getBirthday". Its type is not being narrowed to one of the keys of User. This problem also persist for the args and result variables. They're not being narrowed to their respective types.
Duplicate of #13995 / #20375 ?
... also related to #27808 / #25879?
@jcalz yeah, seems like it's the same issue as #13995.
Most helpful comment
Duplicate of #13995 / #20375 ?
... also related to #27808 / #25879?