代码之家  ›  专栏  ›  技术社区  ›  kevin

如何允许函数参数动态地仅为typescript接口中的一个值?

  •  1
  • kevin  · 技术社区  · 4 年前

    我正在创建一个主题处理函数。

    具有 desiredColor 参数我想通过辩论 只是 接口中的一个键作为基础颜色的类型提供。

    有没有办法限制 渴望的颜色 只是 底层接口的关键值是什么?

    (有没有一种方法可以做到这一点,而不必维护相邻的枚举?)

    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)'
    }
    
    1 回复  |  直到 4 年前
        1
  •  3
  •   MikeM    4 年前

    当然,这很简单

    const colorsHandler = (desiredColor: keyof PaletteColors) =>