-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Labels
Effort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Requires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do thisYou can do thisSuggestionAn idea for TypeScriptAn idea for TypeScript
Milestone
Description
I have the following code:
function logNumber(v: number) { console.log("number:", v); }
function logString(v: string) { console.log("string:", v); }
function foo1(v: number|string) {
switch (typeof v) {
case 'number':
logNumber(v);
break;
case 'string':
logString(v);
break;
default:
throw new Error("unsupported type");
}
}
Error:
Argument of type 'string | number' is not assignable to parameter of type 'number'.
Type 'string' is not assignable to type 'number'.
I was forced to rewrite this using if
statements.
function foo2(v: number|string) {
if (typeof v === 'number') {
logNumber(v);
} else if (typeof v === 'string') {
logString(v);
} else {
throw new Error("unsupported type");
}
}
Please allow using switch statements as type guards.
niieani, NN---, demurgos, ulrichb, svieira and 153 more
Metadata
Metadata
Assignees
Labels
Effort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Requires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do thisYou can do thisSuggestionAn idea for TypeScriptAn idea for TypeScript