-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Union with any produces unexpected result #16958
Comments
This is working as intended. Since |
Oh, is there same way to recover from the declare function apiCall(): string;
function pickOne() {
if (Math.random() > 0.5) {
return 5;
} else {
return apiCall();
}
}
let x = pickOne(); It seems unfortunate to reduce the type to declare function apiCall(): any;
function pickOne() {
if (Math.random() > 0.5) {
return 5;
} else {
return apiCall();
}
}
let x = pickOne(); In this case because some of the return values are typed it appears that accessing any property not inside of |
Do you have another suggestion?
And, statistically, an equal number of cases where you could have anything. 😖 You can always re-narrow... declare function apiCall(): any;
declare function stringsOnly(value: string): void;
function pickOne() {
if (Math.random() > 0.5) {
return 5;
} else {
return apiCall();
}
}
let x = pickOne();
if (typeof x === 'number') {
stringsOnly(x); // Argument of type 'number' is not assignable to parameter of type 'string'.
} TypeScript is trying (and succeeding) at keeping you from writing dangerous code. |
Oh, I guess I just found it odd because usually typescript only allows you to access members common to all parts of a union. For example in the But I see that treating Researching more it looks like this may just be a rehash of #9999, so I will close. |
TypeScript Version: 2.4.0
Code
Expected behavior:
I expected the second case to give an error.
withAny
might only have the properties of a number.Actual behavior:
withAny reduces to the type any, and so does not give an error.
The text was updated successfully, but these errors were encountered: