Skip to content

keyof "a" behaves differently when using a type parameter #23345

Closed

Description

TypeScript Version: 2.9.0-dev.20180411

Code

type A = { [P in keyof "a"]?: boolean }; // { padStart?: boolean | undefined, ... }
type Indirect<T> = { [P in keyof T]?: boolean };
type B = Indirect<"a">; // "a"

declare const a: A;
const b: B = a; // Error

Expected behavior:

No error. B is the same as A.

Actual behavior:

Error: B is the string literal type "a".

Activity

  1. modified the milestones: TypeScript 2.9, on Apr 26, 2018
  2. ahejlsberg commented on Jun 3, 2018

    @ahejlsberg
    Member

    This is working as intended. When instantiating a homomorphic mapped type such as { [P in keyof T]?: boolean } we distribute over union types and leave non-object types unchanged. For example, Indirect<{ x: string } | undefined> is resolved as Indirect<{ x: string }> | undefined. For this reason, Indirect<"a"> is simply "a".

  3. added
    Working as IntendedThe behavior described is the intended behavior; this is not a bug
    and removed
    BugA bug in TypeScript
    on Jun 3, 2018
  4. removed this from the Future milestone on Jun 4, 2018
  5. typescript-bot commented on Jun 18, 2018

    @typescript-bot
    Contributor

    Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

  6. aleclarson commented on Sep 13, 2018

    @aleclarson

    we distribute over union types and leave non-object types unchanged

    What does it mean to "distribute over union types"?

    Also, it seems that as long as I avoid using keyof inside the generic "mapped type" declaration, I can avoid this footgun. See here: https://goo.gl/DakrYm

    What's the practical benefit of making keyof behave differently when inside a generic "mapped type"? Or is it simply a consequence of the current implementation?

  7. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions