【问题标题】:How to add enum type for value of HTMLInputElement如何为 HTMLInputElement 的值添加枚举类型
【发布时间】:2019-05-08 06:24:25
【问题描述】:

如何将自定义枚举类型注入 HTMLInputElement 的值?

我搜索了打字稿文档,但找不到这样做。

enum ValidColor {
  'red',
  'blue',
}

class paintStore {
  wallColor: ValidColor = 'red';

  onPaintClick = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.wallColor = e.target.value // Type 'string' is not assignable to type 'ValidColor'.ts(2322)
  }
}

我尝试创建自定义类型但失败了。

interface ColorTarget {
  value: ValidColor;
}

interface MyColor extends HTMLInputElement {
  target: ColorTarget;
}

onPaintClick = (e: React.ChangeEvent<MyColor>) => {
    this.wallColor = e.target.value // it is not working...
  }

我该怎么做?

【问题讨论】:

    标签: html reactjs typescript events enums


    【解决方案1】:

    那是因为 e.target.value 可以是任何字符串。

    您可能希望以其他方式确保颜色是“红色”或“蓝色”。

    最简单的方法是使用 'as' 关键字告诉编译器“我知道这种颜色将是红色或蓝色”:

    enum ValidColor {
      'red',
      'blue',
    }
    
    class paintStore {
      wallColor: ValidColor = 'red';
    
      onPaintClick = (e: React.ChangeEvent<HTMLInputElement>) => {
        this.wallColor = e.target.value as ValidColor;
      }
    }
    

    更好的方法是使用用户定义的类型保护(更多信息:https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

    enum ValidColor {
      Red = 'red',
      Blue = 'blue'
    }
    
    const validColors: string[] = [ValidColor.Red, ValidColor.Blue];
    
    const isValidColor = (inputColor: string): inputColor is ValidColor => {
      return validColors.indexOf(inputColour) !== -1;
    };
    
    class paintStore {
      wallColor: ValidColor = 'red';
    
      onPaintClick = (e: React.ChangeEvent<HTMLInputElement>) => {
        const maybeColor = e.target.value; // here it's a string
    
        if (isValidColor(maybeColor)) {
            // inside this block, maybeColor is narrowed to type ValidColor...
            this.wallColor = maybeColor;
        }
    
        // Decide what to do if it's not a valid color here
      }
    }
    

    注意函数 isValidColor 的返回类型 - 它告诉 TypeScript 如何调整返回值的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2019-03-31
      相关资源
      最近更新 更多