如何为HTMLINPUTELEMENT值添加枚举类型



我如何将自定义枚举类型注入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...
  }

我该怎么做?

那是因为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/typepes/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-它告诉打字稿如何调整返回值的类型。

最新更新