Skip to content

Destructuring index signature by computed property loses type information #17566

@amirburbea

Description

@amirburbea

TypeScript Version: 2.4.2

Code

type Zomg = { x: number };
type Foobar = { foo: number, bar: Zomg };

const test: { [key: string]: Foobar } = {
  a: { foo: 1, bar: { x: 2 } },
  b: { foo: 3, bar: { x: 4 } },
};

// TSC does not complain about this because destructuring by [key] erroneously makes the compiler infer the type as 'any'.
let key = 'b'; // tried with const and let - results were identical
const { [key]: { bar: { x: x1, y: y1 } } } = test;

// Error: type 'Zomg' has no property 'y' and no string index signature. 
const { ['b']: { bar: { x: x2, y: y2 } } } = test;

Expected behavior:
Both examples (destructure by [key] and destructure by ['b']) should yield identical behavior - in this case an error because there is no y in type Zomg

Actual behavior:
Example 1 is allowed to proceed and more importantly loses all type information about the destructured variables (so x1 is any instead of number whereas x2 correctly is inferred as a number).

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions