Skip to content

Destructuring of mapped object gives implicit any error (regression) #24661

Closed
@ivogabe

Description

@ivogabe

TypeScript Version: 2.9, 3.0.0-dev.20180602

Search Terms:
Generic key mapped object implicit any destructure

Code

function foo<T extends string>(key: T, obj: { [_ in T]: number }) {
  const { [key]: bar } = obj; // Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature.
  bar; // bar : any

  // Note: this does work:
  const lorem = obj[key];
}

With compiler option noImplicitAny.

Expected behavior:
No error, the definitions for bar and lorem are treated as equal. This used to work in TS 2.8. The type of bar is number.

Actual behavior:
Error on the definition of bar:

Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature.

The type of bar is any.

Playground Link:
http://www.typescriptlang.org/play/index.html#src=function%20foo%3CT%20extends%20string%3E(key%3A%20T%2C%20obj%3A%20%7B%20%5B_%20in%20T%5D%3A%20number%20%7D)%20%7B%0A%20%20const%20%7B%20%5Bkey%5D%3A%20bar%20%7D%20%3D%20obj%3B%0A%20%20bar%3B%0A%0A%20%20const%20lorem%20%3D%20obj%5Bkey%5D%3B%20%20%0A%7D

Notice that the type of bar is any. Set noImplicitAny to see the error.

Related Issues:

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions