It seems that there might be a bug in Typescript regarding the behavior described below. I have submitted an issue on GitHub to address this problem, and you can find it at this link. The code example provided in that issue explains the situation more clearly than the code snippet presented here.
Let's examine the code in the file
undefined-literal-string-field.ts
:
class Foo {
public foo: 'foo';
}
const foo = new Foo();
console.log('Foo ', foo.foo);
Notice how the property Foo.foo
has a literal string type, but it does not include undefined
. This means the type is strictly just 'foo'
, without allowing 'foo' | undefined
.
In TypeScript 2.2, this code actually compiles with the flag --strictNullChecks
:
$ node_modules/.bin/tsc --version
Version 2.2.2
$ node_modules/.bin/tsc --strictNullChecks undefined-literal-string-field.ts
However, when executed, the field is undefined
:
$ node undefined-literal-string-field.js
Foo undefined
This inconsistency arises because the property remains uninitialized in the resulting JavaScript code:
var Foo = (function () {
function Foo() {
}
return Foo;
}());
var foo = new Foo();
console.log('Foo ', foo.foo);
I may have misinterpreted the implications of --strictNullChecks
, but as far as I understand, this flag should prevent undefined
values unless explicitly allowed through union types like 'foo' | undefined
. However, that's not what's happening in this case.
Why does the compiler permit accessing an uninitialized field in this scenario where its type does not allow the value undefined
? Doesn't this pose a potential unsoundness?
Furthermore, considering that the type of foo
only permits a single value, shouldn't the compiler initialize it with that one valid value automatically?
What am I overlooking here?