File: inferentiallyTypingAnEmptyArray.js

package info (click to toggle)
node-typescript 4.9.5%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 533,908 kB
  • sloc: javascript: 2,018,330; makefile: 7; sh: 1
file content (21 lines) | stat: -rw-r--r-- 1,178 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//// [inferentiallyTypingAnEmptyArray.ts]
// April 2014, Section 4.6:
//      In the absence of a contextual type, the type of an array literal is C[], where C is the
//      Undefined type(section 3.2.6) if the array literal is empty, or the best common type of
//      the element expressions if the array literal is not empty.
//      When an array literal is contextually typed(section 4.19) by an object type containing a
//      numeric index signature of type T, each element expression is contextually typed by T and
//      the type of the array literal is the best common type of T and the types of the element
//      expressions.
//
// While the spec does not say it, an inferential type causes an empty array literal to have
// the undefined[] type. In other words, the first clause from the excerpt above applies even
// though there is a "contextual type" present. This is the intention, even though the spec
// seems to imply the contrary.
// Therefore, the following access to bar should not cause an error because we infer
// the undefined[] type.
declare function foo<T>(arr: T[]): T;
foo([]).bar;

//// [inferentiallyTypingAnEmptyArray.js]
foo([]).bar;