-
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
When strictNullChecks is true, enable parser to detect null checking further than the current depth #11190
Comments
All you have to do is add a type predicate return type: function isNull(a: any): a is null {
return a == null;
} and this example works as you'd like it to. |
Thanks, is this documented anywhere? |
It would be great if typescript could automatically detect this. For example calling lodash methods that check for null now must be updated. Regarding LoDash and related libraries, you'd have to fix it in this manner: Old Lodash d.ts:
New Lodash d.ts:
|
See "User-Defined Type Guards" at https://www.typescriptlang.org/docs/handbook/advanced-types.html |
How would this work for assertions? Since JS/TS does not have
Am I correct to assume the best solution would be this:
This is were I wish TypeScript was more implicit when it comes to null checks. Adding the type explicitly kind of feels like defeating the purpose of the the strict null check. If I'm forcing the compiler to use a particular type, I now loose the benefit of strict null checking. |
A slightly different pattern that works much better: function fail(message: string): never {
throw new Error(message);
}
class Demo {
name: string | null;
logNullableNameWithAssert() {
if (this.name === null)
return fail("Name cannot be null");
this.log(this.name);
}
log(message: string) {
console.log(message);
}
} The key here is |
Thanks! |
If I cache the results of a null check in a local variable it will fail. Do I have to always check for null and/or undefined inline?
|
Once a type guard goes into a variable, it's no longer tracked (otherwise we'd have to track all function call arguments at all points throughout the program, which would be too expensive). |
Hi, I found this issue looking how to make assertions on null. After reading this I have 2 questions: 1. Are there any plans to introduce not null | undefined asserts?
It think it would be similar to user-defined type guards, but for not null asserts. But they wouldn't need an 2. According to a previous comment, when using a function whose return type is
Are there plans to remove this return restriction when a function returns |
For example, both methods
logNullableNameCustomNullCheck
andlogNullableName
check if thename
variable is null before usage, butlogNullableNameCustomNullCheck
fails because the null check occurs in another method. If I have a custom helper method designed to check for nulls, I can no longer call it when strict null checking is enabled.The text was updated successfully, but these errors were encountered: