Skip to content

Type checking Javascript object literals is not open-ended in Maps #15618

@ccprog

Description

@ccprog

Seen in VS Code 1.12.1 == TypeScript 2.3

In a Javascript context, type-checking with @ts-check should treat objects as open maps, according to the wiki page. This does not work if a Map is declared with member objects that have varying properties:

// @ts-check

const map = new Map([
    ['a', {x: 1}],
    ['b', {y: 2}]
]);

const arr = [
    ['a', {x: 1}],
    ['b', {y: 2}]
];
const map2 = new Map(arr);

The y: 2 in line 5 raises this error message:

The type argument for type parameter 'V' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
Type argument candidate '{ x: number; }' is not a valid type argument because it is not a supertype of candidate '{ y: number; }'.
Object literal may only specify known properties, and 'y' does not exist in type '{ x: number; }'.

The arr in line 12 raises a slightly different message:

Argument of type '((string | { [x: string]: any; x: number; })[] | (string | { [x: string]: any; y: number; })[])[]' is not assignable to parameter of type '[any, any][]'.
Type '(string | { [x: string]: any; x: number; })[] | (string | { [x: string]: any; y: number; })[]' is not assignable to type '[any, any]'.
Type '(string | { [x: string]: any; x: number; })[]' is not assignable to type '[any, any]'.
Property '0' is missing in type '(string | { [x: string]: any; x: number; })[]'.

It might be arguable whether this is a type checking bug, or whether the wiki documentation is misleading, as the JS relaxation of checking behaviour should only provide for late-adding members.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions