An uninitialized field with a null literal string type undefined despite strict zero checks?

I believe that the following behavior is a mistake in Typescript and openly https://github.com/Microsoft/TypeScript/issues/15170 . The sample code in this release demonstrates the problem more clearly than the code below.


Consider the following code in undefined-literal-string-field.ts:

class Foo {
  public foo: 'foo';
}

const foo = new Foo();

console.log('Foo ', foo.foo);

Note that it Foo.foohas a string type of string , but does not include undefined. In other words, note that the type is simple 'foo', but not 'foo' | undefined .

In Typescript 2.2, this code compiles with--strictNullChecks :

$ node_modules/.bin/tsc --version
Version 2.2.2    
$ node_modules/.bin/tsc --strictNullChecks undefined-literal-string-field.ts

However , the runtime field : undefined

$ node undefined-literal-string-field.js
Foo  undefined

, JS-:

var Foo = (function () {
    function Foo() {
    }
    return Foo;
}());
var foo = new Foo();
console.log('Foo ', foo.foo);

, --strictNullChecks, , , undefined , undefined, .. 'foo' | undefined. .

Typescript , undefined? ?

-, foo - , ?

?

+4
2

, foo . console.log, foo ( , , , ).

why the compiler wont initialize the field? - foo: 'foo' - . .

, foo , , :

class Foo {
    public foo: 'foo' = 'foo';
}

.

0

const foo =new Foo();

class Foo {

  public foo : 'foo';

}
let foo: 'foo';

console.log('Foo ', foo.foo);

 error TS2454: Variable 'foo' is used before being assigned.

,

public foo= 'foo';
0

Source: https://habr.com/ru/post/1674638/


All Articles