Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何创建验证字符串格式的typescript类型?i、 检查字符串是否为有效的css长度属性_Reactjs_Typescript - Fatal编程技术网

Reactjs 如何创建验证字符串格式的typescript类型?i、 检查字符串是否为有效的css长度属性

Reactjs 如何创建验证字符串格式的typescript类型?i、 检查字符串是否为有效的css长度属性,reactjs,typescript,Reactjs,Typescript,所以我有一个react项目,其中组件采用高度支撑。该道具用于确定组件的css属性(我使用情感库) 比如说, render(){ const styles=css` 高度:${this.props.height}; `; 返回( ... ); } 我有一个高度类型,目前是 界面道具{ 高度:数字|字符串; } 我希望创建一个类型来验证高度单位是否为字符串,而不是检查高度是否为字符串的类型 比如说, 10px是一个有效的道具,因此没有类型脚本错误 10xp将抛出类型脚本错误 有没有办法创建一个类

所以我有一个react项目,其中组件采用高度支撑。该道具用于确定组件的css属性(我使用情感库)

比如说,

render(){
const styles=css`
高度:${this.props.height};
`;
返回(
...
);
}
我有一个高度类型,目前是

界面道具{
高度:数字|字符串;
}
我希望创建一个类型来验证高度单位是否为字符串,而不是检查高度是否为字符串的类型

比如说,

10px
是一个有效的道具,因此没有类型脚本错误

10xp
将抛出类型脚本错误

有没有办法创建一个类型来检查第一部分是数字,第二部分是这些值之一

键入cssabsolutionunit=“cm”|“mm”|“in”|“px”|“pt”|“pc”;
输入CssRelativeUnit=“em”|“ex”|“ch”|“rem”|“vw”|“vh”|“vmin”|“vmax”|“%”;

我希望以typescript编译器会抛出错误的方式执行此操作,因此仅使用正则表达式在渲染时进行验证并不能真正完成此工作

不幸的是,这听起来像是编译器完成工作后在运行时确定的。但是,如果您提前知道将要传递的值,您可以创建一个接口并为将要传递的类型实现类

大概是这样的:

interface CssUnit {
  getValue(): string;
}

class PxUnit implements CssUnit {
  private unit: string;

  constructor(value: number) {
    this.unit = value + "px";
  }

  getValue(): string {
    return this.unit;
  }
}
那么

interface Props {
  height: CssUnit;
}
您所要做的就是传入一个实现的类


希望有帮助

您可以使用正则表达式类型,字符串结尾为所需的单位值之一。据我所知,没有办法定义这样的类型。有一个新的版本,但似乎没有任何努力在不久的将来的版本中包含这样的功能。@Rikin我不知道typescript中有这样的类型。你能提供一个来源吗?
const regex:RegExp=/my_regex/
实际上我错误地键入了
type
availability