-
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
Optional chaining, proper infer in type guard #34974
Comments
This is a little tricky; TS sees the |
I have a similar issue with type guards. This compiles: type Person = { name: string; }
const getName = (person?: Person): string => {
return typeof person?.name === 'string' ? person?.name : '';
}; But this does not: type Person = { name: string; }
const isString = (value: any): value is string => {
return typeof value === 'string';
};
const getName = (person?: Person): string => {
return isString(person?.name) ? person?.name : '';
};
// Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'. I would have expected these examples to be equivalent. Is there another way to write the |
I’ve encountered the same problem. |
@lo1tuma Sorry, but no. As Ryan said, type guard is not a part of control flow analytics, so type narrowing is not working. Here is a compare:
|
TypeScript knows how to do this properly if you directly check that the chained variable is not null/undefined. It only fails if you use a type guard to check it. This works: if (animal?.breed?.size != null) {
return animal.breed.size;
} else {
return undefined;
} This doesn't: if (!isNil(animal?.breed?.size)) {
return animal.breed.size; // Error: Object is possibly 'undefined'. (2532)
} else {
return undefined;
}
function isNil(value: unknown): value is undefined | null {
return value == null;
} Here is a playground link demonstrating this. I don't know what TypeScript is doing internally, but the fact that one works and the other doesn't is what makes this feel like a bug to me rather than a type system limitation. |
This might be more tractable to fix now that |
What about ternary conditions? Would it be possible to also narrow those like here
here we also know that if the condition in @RyanCavanaugh any hope for that? |
TypeScript Version: 3.7.0
Search Terms: optional chaining
Code
The code fix is by adding additional checks or additional temporary variables:
Expected behavior:
TypeScript is able to infer that optional chaining was used as an argument, what means that typeguard is checking the whole chain.
Actual behavior:
TypeScript needs a code change in order to understand that optional chaining already checked other values from being null | undefined.
The text was updated successfully, but these errors were encountered: