Zoeken op website

Typescript const enum index handtekening


export const enum Outcome {
  primary = 'primary',
  success = 'success',
  failure = 'failure'
}

export const buttonColors: { [key in Outcome]: string } = { primary: '#007aff', success: '#00C260', failure: '#F56B62' };

// example 1
buttonColors[Outcome.primary]; // works

// example 2 - interface doesn't work

interface IProps {
  outcome: Outcome;
}

const first: IProps = { outcome: Outcome.primary };
buttonColors[first.outcome]; // Error: Element implicitly has an 'any' type because type '{ primary: string; success: string; failure: string; }' has no index signature.

// example 3 - class - works
class Props {
  // notice this is class
  outcome: Outcome;
}

const second: Props = new Props();
second.outcome = Outcome.primary;
buttonColors[second.outcome]; // works

In al de bovenstaande gevallen wordt const enum gebruikt om toegang te krijgen tot buttonColors, maar het is niet duidelijk waarom het niet werkt wanneer de toegang via een interface is.

Elke hulp wordt gewaardeerd.

Dank je,