如何创建验证字符串格式的打字稿类型?即检查字符串是否有效 CSS 长度属性



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

例如

render() {
const styles = css`
height: ${this.props.height};
`;
return (
<div style={styles}>
...
</div>
);
}

我有一个高度类型,目前是

interface Props {
height: number | string;
}

我想创建一个类型来验证高度单位是否为字符串,而不是使用检查高度是否为字符串的类型。

例如

10px是一个有效的道具,所以没有打字稿错误。

10xp将抛出打字稿错误。

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

type CssAbsoluteUnit = "cm" | "mm" | "in" | "px" | "pt" | "pc";
type CssRelativeUnit = "em" | "ex" | "ch" | "rem" | "vw" | "vh" | "vmin" | "vmax" | "%";

我想以一种打字稿编译器会抛出错误的方式做到这一点,所以只使用正则表达式来验证渲染并不能真正完成这项工作。

这可以通过模板文本类型来实现,尽管在可能错误地传递为有效的内容方面存在一些限制:

type Unit = '%' | 'px' | 'em' | 'vh' | 'vh'
type HeightProp = `${number}${Unit}`

const valid: WidthValue[] = ['10%', '100px', '100em', '100vh', '100vw'] // Valid
const invalid: WidthValue[] = ['10leagues', 'one-hundred-px'] // Error
const falseNegative: WidthValue[] = ['10 px', '0e1px'] // Invalid but passes

此示例并不详尽,但可以将该概念扩展到涵盖更广泛的 CSS 属性和有效值。

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

像这样:

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;
}

您所要做的就是传入一个已实现的类。

希望对您有所帮助!

最新更新