[英]How to type a color prop?
My component accepts an overlay
prop that is supposed to be a valid CSS color.我的组件接受一个应该是有效 CSS 颜色的overlay
道具。
When I CTRL + Click
on a color
property in style object, the type definition comes from a csstype
folder inside node_modules.当我CTRL + Click
样式对象中的color
属性时,类型定义来自csstype
文件夹。 The type definition for CSS color property is defined as Property.Color
. CSS 颜色属性的类型定义定义为Property.Color
。 I imported that type into my component and used it as my overlay
prop's type but it ends up being any
when I try to use that component.我将该类型导入到我的组件中并将其用作我的overlay
道具的类型,但是当我尝试使用该组件时它最终是any
类型。
My component's type definition:我的组件的类型定义:
import { Property } from "../node_modules/csstype/index";
export interface BlurredComponentProps {
overlay?: Property.Color;
}
Here is how it looks when I use the component:这是我使用组件时的样子:
So my question is, how to properly type a prop that is supposed to take only valid CSS colors and give error if non-color value is given?所以我的问题是,如何正确键入一个应该只采用有效 CSS 颜色的道具,如果给出了非颜色值,则给出错误?
Thanks谢谢
This one is pretty hard to encode in TypeScript's type system.这个很难在 TypeScript 的类型系统中编码。 I believe a full fledged parser can do a better job in both speed and accuracy.我相信一个成熟的解析器可以在速度和准确性方面做得更好。
Anyway, if you really want to get some typecheking for your color
values from typescript then let's start with w3c color property description :无论如何,如果你真的想从打字稿中对你的color
值进行一些类型检查,那么让我们从 w3c 颜色属性描述开始:
Values: <color value> | <color keyword> | currentColor | transparent | inherit
playground link for those who don't need explanations and what to look right into the code.为那些不需要解释和直接查看代码的人提供的操场链接。
Well, color keyword
, currentColor
, transparent
and inherit
are pretty straightforward:好吧, color keyword
、 currentColor
、 transparent
和inherit
非常简单:
type Color = ColorValue | ColorKeyword | 'currentColor' | 'transparent' | 'inherit'
type ColorKeyword =
| "black"
| "silver"
| "gray"
...
| "rebeccapurple"
The tricky part is <color value>
:棘手的部分是<color value>
:
The color can be specified as
* a hexadecimal RGB value: #faf or #ffaaff
* a RGB value: rgb(255, 160, 255) or rgb(100%, 62.5%, 100%)
Each value is from 0 to 255, or from 0% to 100%.
* a RGBA value: rgba(255, 160, 255, 1) or rgba(100%, 62.5%, 100%, 1)
This variant includes an “alpha” component to allow
specification of the opacity of a color. Values are
in the range 0.0 (fully transparent) to 1.0 (fully opaque).
* a HSL value: hsl(0, 100%, 50%)
A triple (hue, saturation, lightness). hue is an
angle in degrees. saturation and lightness are
percentages (0-100%).
* a HSLA value: hsla(0, 100%, 50%, 1)
This variant includes an “alpha” component to allow
specification of the opacity of a color. Values are
in the range 0.0 (fully transparent) to 1.0 (fully opaque).
hexadecimal RGB value
is still ok-ish: hexadecimal RGB value
仍然可以:
type HexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
type Hex3 = `${HexDigit}${HexDigit}${HexDigit}`
type RGBColor<T extends string> =
Lowercase<T> extends `#${Hex3}`
? T
: Lowercase<T> extends `#${Hex3}${infer Rest}`
? Rest extends Hex3
? T
: never
: never
We have to introduce type variable T
.我们必须引入类型变量T
。 Otherwise 'flat' union type:否则为“扁平”联合类型:
type RGBColor = `#${Hex3}` | `#${Hex3}${Hex3}`
is going to consist of 16^3 + 16^6
constituents that's far beyound 100000
typescript limit for union types.将由16^3 + 16^6
成分组成,远远超过联合类型的100000
打字稿限制。
Let's introduce some helper types to work with numbers.让我们介绍一些辅助类型来处理数字。 We have to check the percents are not greater than 100%
and end with %
character.我们必须检查百分比不大于100%
并以%
字符结尾。
type DecDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
type Digits0to4 = '0' | '1' | '2' | '3' | '4'
type OnlyDecDigits<T extends string> =
T extends `${DecDigit}${infer Rest}`
? Rest extends ''
? 1
: OnlyDecDigits<Rest>
: never
type IsDecNumber<T extends string> =
T extends `${infer Integer}.${infer Fractional}`
? Integer extends ''
? OnlyDecDigits<Fractional>
: Fractional extends ''
? OnlyDecDigits<Integer>
: OnlyDecDigits<Integer> & OnlyDecDigits<Fractional>
: OnlyDecDigits<T>
type IntegerPart<T extends string> =
T extends `${infer I}.${infer F}`
? I
: T
type IsInteger<T extends string> =
1 extends IsDecNumber<T>
? T extends IntegerPart<T>
? 1
: never
: never
type Less100<T extends string> =
IsDecNumber<T> extends 1
? IntegerPart<T> extends `${DecDigit}` | `${DecDigit}${DecDigit}` | '100'
? 1
: never
: never
type IsPercent<T extends string> =
'0' extends T
? 1
: T extends `${infer P}%`
? Less100<P>
: never
Also color values must be integers and not greater than 255
:此外颜色值必须是整数且不大于255
:
type Color255<T extends string> =
1 extends IsInteger<T>
? T extends `${DecDigit}`
| `${DecDigit}${DecDigit}`
| `1${DecDigit}${DecDigit}`
| `2${Digits0to4}${DecDigit}`
| `25${Digits0to4 | '5'}`
? 1
: never
: never
so, any color value can be encoded as an integer number in [0..255]
range or a percent:因此,任何颜色值都可以编码为[0..255]
范围内的整数或百分比:
type IsColorValue<T extends string> = IsPercent<T> | Color255<T>
Adding utility Trim
type to trim extra spaces on both ends:添加实用程序Trim
类型以修剪两端的额外空间:
type WhiteSpace = ' '
type Trim<T> = T extends `${WhiteSpace}${infer U}`
? Trim<U>
: T extends `${infer U}${WhiteSpace}`
? Trim<U>
: T;
That's enough for rgb
:这对于rgb
足够了:
type RGB<T extends string> =
T extends `rgb(${infer R},${infer G},${infer B})`
? '111' extends `${IsColorValue<Trim<R>>}${IsColorValue<Trim<G>>}${IsColorValue<Trim<B>>}`
? T
: never
: never
For rgba
/ hsla
we'll need opacity.对于rgba
/ hsla
我们需要不透明度。 Here we just ask for any valid number or a percent:在这里,我们只要求输入任何有效数字或百分比:
type Opacity<T extends string> = IsDecNumber<T> | IsPercent<T>
Now we can check rgba
values:现在我们可以检查rgba
值:
type RGBA<T extends string> =
T extends `rgba(${infer R},${infer G},${infer B},${infer O})`
? '1111' extends `${IsColorValue<Trim<R>>}${IsColorValue<Trim<G>>}${IsColorValue<Trim<B>>}${Opacity<Trim<O>>}`
? T
: never
: never
Adding degree checker for hsl
/ hsla
:为hsl
/ hsla
添加学位检查器:
type Degree<T extends string> =
1 extends IsInteger<T>
? T extends `${DecDigit}`
| `${DecDigit}${DecDigit}`
| `${'1' | '2'}${DecDigit}${DecDigit}`
| `3${Digits0to4 | '5'}${DecDigit}`
| '360'
? 1
: never
: never
and finally we can cover the last cases:最后我们可以涵盖最后一种情况:
type HSL<T extends string> =
T extends `hsl(${infer H},${infer S},${infer L})`
? `111` extends `${Degree<Trim<H>>}${IsPercent<Trim<S>>}${IsPercent<Trim<L>>}`
? T
: never
:never
type HSLA<T extends string> =
T extends `hsla(${infer H},${infer S},${infer L},${infer O})`
? `1111` extends `${Degree<Trim<H>>}${IsPercent<Trim<S>>}${IsPercent<Trim<L>>}${Opacity<Trim<O>>}`
? T
: never
:never
So our final type will look like that:所以我们的最终类型看起来像这样:
type ColorValue<T extends string> = HexColor<T> | RGB<T> | RGBA<T> | HSL<T> | HSLA<T>
type Color<T extends string> = ColorValue<T> | ColorKeyword | 'currentColor' | 'transparent' | 'inherit'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.