Skip to content

keyof on types originating from javascript object literals is (nearly) useless #25987

Closed
@weswigham

Description

@weswigham

TypeScript Version: 3.1.0-dev.201xxxxx

Search Terms:

Code

In a js file:

// @ts-check
const x = {
    y: 12
};

/** @type {keyof typeof x} */
const q = "z"; // Assignment is allowed, but is not what was desired!

Expected behavior:
keyof returns the keys the object actually has or is declared with.

Actual behavior:
keyof returns string | number, thanks the the any-index signature shoved into every object literal expression's type in JS.

This came up on DefinitelyTyped - strongly typing react's propTypes is virtually impossible because all of the key filtering and mapping operations (eg, Exclude) just don't work on any JS object literals (unless all of your keys are unique symbols (nobody would do this, I don't think), since those aren't mangled by subtype reduction with the index signature).

cc @mhegazy This is a blocker in rolling out the better React inferences to our JS users.

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