microsoft / microsoft/TypeScript

Conditional types don't work with Mapped types when you extend enum keys

Ouverte
#27,022 0 commentaires 0 réactions 1 personne assignée Voir sur GitHub

@weswigham y travaille déjà.

Depuis le 21/9/2018.

Needs Investigation
Langage dominant
Go
Étoiles
111k
Forks
14.3k
Merge moyen
2 j 4 h
PR mergées (30 j)
132

Description

TypeScript Version: 3.0.3, 3.1.0-dev.20180907

Search Terms:
mapped, conditional, enum, extends
Code

enum Commands {
  one = "one",
  two = "two",
  three = "three"
}

const SpecialCommandsObj = {
  [Commands.one]: Commands.one,
  [Commands.two]: Commands.two,
};

// a and b are correct
type a = Commands.one extends keyof typeof SpecialCommandsObj ? null : any; // null - ok
type b = Commands.three extends keyof typeof SpecialCommandsObj ? null : any; // any - ok

interface CommandAction {
  execute(element: any): any;
}

interface SpecialCommandAction {
  execute(element: null): any;
}

type CommandsActions = {
    [Key in keyof typeof Commands]:  Key extends keyof typeof SpecialCommandsObj ? SpecialCommandAction : CommandAction
};

const Actions: CommandsActions = {
  [Commands.one]: {
      // ERROR
    execute: (element) => {} // ELEMENT IS ANY, NOT NULL
  },
  [Commands.two]: {
      // ERROR
    execute: (element) => {} // ELEMENT IS ANY, NOT NULL
  },
  [Commands.three]: {
    execute: (element) => {}
  },
}

Expected behavior:
In the Actions object the argument of the execute method for Commands.one and Commands.two should be of type null, not any
Actual behavior:
element is always any,

type inference for type a and b are fine so it only occurs when you use mapped types

it works if you don't use enums as keys in SpecialCommandObj. Swap your SpecialCommandsObj with this one and it will start working

const SpecialCommandsObj = {
  "one": Commands.one,
  "two": Commands.two,
};

Playground Link: https://bit.ly/2QmdTIo

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.