Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

47
Views
How to allow a function argument to dynamically only be one value from a typescript interface?

I am creating a theme handling function.

The function that has a desiredColor parameter. I want passed in argument to only be one of the keys from the interface provided as the type for the underlying colors.

Is there a way to restrict the desiredColor to only be one of the key values of the underlying interface?

(is there a way to do this without also having to maintain an adjacent enum?)

const handleThemeColors = (mode: ThemeMode): any => {
  const colorsHandler = (desiredColor: Array<keyof PaletteColors>) =>
  // goal ^ desiredColor can be either: blueDark, blueMain, or blueLight
 {
    switch (mode) {
      case 'light':
        return colorsLight[desiredColor];
      default:
        return colorsDark;
    }
  };
 ...
}
interface PaletteColors {
  blueDark: string;
  blueMain: string;
  blueLight: string;
}

const colorsLight: PaletteColors = {
  blueDark: 'rgba(2, 189, 185,1)',
  blueMain: 'rgba(0, 203, 198,1)',
  blueLight: 'rgba(147, 231, 229,1)'
}
7 months ago · Santiago Trujillo
1 answers
Answer question

0

Surely, it's as simple as

const colorsHandler = (desiredColor: keyof PaletteColors) =>
7 months ago · Santiago Trujillo Report
Answer question
Find remote jobs