-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Definite assignment assertions #20166
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
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We will need some tests for the new token
|
@ahejlsberg what's the best way to add suppression at call site, not globally for the variable? See your second example, like this: function f() {
let x: number; <---- reluctant to suppress checks for real code
doSomethingWithCallback(() => {
x = 1;
});
console.log( x as x! ); <----- prefer to suppress checks at diagnostic call site only
} |
|
@mihailik I think you are looking for the pre-existing not-null assertion: console.log( x! ) |
|
@gcnew great, but would that work in this case? |
|
@mihailik I tested it before posting just to make sure and it worked. Thinking about it for a second time, is your intention to mark properties as "assigned" in a class constructor under |
|
@gcnew I was referring to the second example in the original post. It's Thanks for the syntax!! |
|
Any chance this feature could expand a bit to solve ~ I know, I know... ~#9998? Wish: Instead of the |

This PR introduces the ability for a variable or property declaration to include a definite assignment assertion in the form of a
!character following the variable or property identifier. A definite assignment assertion instructs the control flow analyzer to always consider the variable definitely assigned, even when the analyzer is unable to prove it.In the example above, if it is known that
setDatawill always be called beforegetData, there is no need to initialize thedataproperty upon construction. However, the control flow analyzer can't make that assumption, and in--strictPropertyInitializationmode (see #20075) it reports an error unless a definite assignment assertion!is included.In the example above, if it is known that
doSomethingWithCallbackwill always invoke the callback before returning, there is no need to initializexin its declaration. However, the control flow analyzer conservatively assumes thatxis used before being assigned in theconsole.log(x)call and reports an error. A definite assignment assertion can now be included in the declaration to suppress this error.Definite assignment assertions are permitted only in the following cases:
letorvarvariable declaration, provided the variable has a type annotation and no initializer.Related issues: #11463, #12855, #13811.