top | item 14094331

(no title)

curveship | 9 years ago

Sort of. Strict null checking now lets you distinguish between the types Foo[] and (Foo | undefined)[]. The first will type with the assumption that there are no out of bounds indices (which, as you say, could be wrong). The second will require you to always check the result of array dereferences to see if they're undefined before you reference the object.

  var foos1 = [] as Foo[],
      foos2 = [] as (Foo | undefined)[];
  
  // ... later
  
  var foo1 = foos1[i],
      foo2 = foos2[i];

  foo1.bar(); // types fine, TS assumes non-undefined
  foo2.bar(); // TS type error, as you haven't checked undef
  if (foo2) foo2.bar(); // types fine, undef excluded

discuss

order

yoklov|9 years ago

This isn't the issue I'm describing at all.

E.g. if I missed a bounds check, and access past the end of a `Foo[]`, it would be typed as `Foo` (and not `Foo | undefined`), but really be `undefined.

Consider this code.

    var foos: Foo[] = [new Foo()];
    foos[1].bar();

foos[1] will be undefined (since it's past the end of the array) but will typecheck as a Foo.

Obviously it's bad if I forget a bounds check, but it's similarly bad if I forgot a null check.

Of course, I understand why this issue exists, but it is an issue.

vosper|9 years ago

> (Foo | undefined)[]

This says "either an array of Foo or an array of undefined", right? Not "either an array of Foo or just undefined"?

jiaweihli|9 years ago

No, (Foo | undefined)[] means an array of elements that are either of type Foo or are undefined.

Foo[] | undefined[] means either 1) an array of Foo, or 2) an array of undefined.

josteink|9 years ago

It says an array whose elements can be either Foo or undefined.