No widening in strict null checking mode #8944

merged 3 commits into from Jun 2, 2016


None yet

3 participants

ahejlsberg commented Jun 2, 2016 edited

This PR fixes #8878 and supercedes #8907. The PR implements the following three changes:

  • Empty array literals ([]) have type never[].
  • No widening of empty array literals in strict null checking mode. Since we already don't widen null and undefined literals in strict null checking mode, this means that the concept of widening now exists only for backwards compatibility with classic type checking mode.
  • In classic type checking mode we only widen the null and undefined types when they originate in null and undefined literals used in expressions. We don't widen null and undefined when they're used as type annotations. This is essentially a bug fix.

Since we expect --strictNullChecks to almost always be used in combination with --noImplicitAny, it seems pointless to widen the type of empty array literals from never[] to any[] since we'll immediately report an implicit any error following the widening. It seems better to preserve the more specific never[] type and require the programmer to add a type annotation if the array is actually going to be modified.

So, where the experience previously was

// Compile with --strictNullChecks and --noImplicitAny
var a = [];  // Error: Variable 'a' implicitly has an 'any[]' type

the experience now becomes

// Compile with --strictNullChecks
var a = [];  // Type of a is never[]
a.push(5);   // Error: Argument of type 'number' is not assignable to parameter of type 'never'

Of course, when a type annotation is present there is no error:

// Compile with --strictNullChecks
var a: number[] = [];

By altogether avoiding widening we solve some long standing issues in #531 and #1436.

ahejlsberg added some commits Jun 2, 2016
@ahejlsberg ahejlsberg Add non-widening forms of null and undefined 2517238
@ahejlsberg ahejlsberg Add tests
@ahejlsberg ahejlsberg Remove unused variable
mhegazy commented Jun 2, 2016


@ahejlsberg ahejlsberg merged commit 3853555 into master Jun 2, 2016

2 checks passed

continuous-integration/travis-ci/pr The Travis CI build passed
continuous-integration/travis-ci/push The Travis CI build passed
@weswigham weswigham deleted the reviseWidening branch Aug 11, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment