Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21931

Typescript: question sign after type annotation in assignment expression (nullable type?)

Today I discovered I can do this:

let foo: string? // foo now has type string | null

What's that? I cannot find a reference of it in the TS handbook. Can someone point to it?

Another (not less important though) question is: why the heck it produces string | null and not string | undefined? Because the latter would be much more useful since a declared (but not initialized) variable usually has type undefined. This is even more confusing, given that question sign in interfaces give us ... | undefined type.

P.S. My TS version is 3.4.3

UPD. It seems it's a bug. Worked only if followed by an if statement:

let foo: string?
if(1) {

}

Then, again, ok it's a bug, but why it produced string | null?

Upvotes: 2

Views: 1123

Answers (2)

jcalz
jcalz

Reputation: 329598

Looks like this is intended to support some version of JSDoc nullable-type (that is, | null) notation for using TypeScript to check JavaScript files. If you start using JSDoc syntax in a TypeScript file, I'd expect to see an error... which is what I see in the Playground:

let foo: string?; // error!
// JSDoc types can only be used inside documentation comments.

If you're using that notation in a TypeScript file and not seeing an error, I'd consider that to be a bug (or maybe you have some interesting compiler options set).


I say "some version" because the official JSDoc way of annotating types as nullable is to use ? as a prefix operator, not as a postfix operator. That is, JSDoc says to use @type {?string} instead of @type {string?}.

Apparently, Google's Closure Compiler unofficially supports postfix-?, and I guess TypeScript does too. But this doesn't conform to the official JSDoc standard, and might even end up being removed from TS. So I wouldn't rely on it sticking around even if you are using JSDoc type comments in your code.

Okay, hope that helps. Good luck!

Upvotes: 1

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21931

Turns out it is this feature being implemented and it requires ; after ? to work properly in all cases.

Upvotes: 1

Related Questions