microsoft / microsoft/TypeScript

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

Aperta
#27,022 0 commenti 0 reazioni 1 assegnatario Vedi su GitHub

@weswigham ci sta già lavorando.

Dal 21/9/2018.

Needs Investigation
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.