-
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
strictNullChecks blocks safe typeof capture #16108
Comments
Also note: It appears you cannot use the non-null assertion operator to appease the compiler here. |
That error message is indeed strange in type position. What type would you expect the {
prop: string
} |
Ah, I suppose it can't. I'm trying to capture the type |
The simplest fix is to create an extra local which is obviously not ideal or, as you need to test declare function maybeGetNestedValue(): Nested | null;
const nested = maybeGetNestedValue();
const notNullNested = nested!;
const child: typeof notNullNested.child = {
prop: 'value'
}; |
You can also use |
@andy-ms right, thank you! I keep forgetting about that syntax. It's definitely the way to go here. |
Feels like property access in |
Easy PR if anyone wants to grab this |
Discussed this again in #22445. Conclusion, with So the sample in the OP would look like: const child: NonNullable<typeof nested>["child"] = {
prop: 'value'
} |
Sorry if this is a dupe - I tried searching but github's search isn't great.
TypeScript Version: 2.3.1
Code
TypeScript Playground link
Note: You need to manually enable strictNullChecks under the options for this link. If I enable it and try to share it says the text buffer is too big to share.
Expected behavior: I would expect to be able to use
typeof
to capture the type of this nested field, since as you can see in the emitted code in the TypeScript Playground link, there is no dereference of thenested
field emitted, so the code should always be safe.Actual behavior: The strictNullChecks flag raises an error because the
nested
field may benull
.The text was updated successfully, but these errors were encountered: