I have the following example code snippet:
type Color = string; interface Props { color: Color; text: string; } function Badge(props: Props) { return `<div style="color:${props.color}">${props.text}</div>`; } var badge = Badge({ color: '#F00', text: 'Danger' }); console.log(badge);
Playground
I'm trying to get a build error if the color is invalid, like so:
var badge = Badge({ color: 'rgba(100, 100, 100)', text: 'Danger' });
Is there a way to define Color
so that it allows only strings matching one of the following patterns?
#FFF
#FFFFFF
rgb(5, 5, 5)
rgba(5, 5, 5, 1)
hsa(5, 5, 5)
I realize that there are colors like red
and white
but that might make this harder to answer if Color
can accept those.
The following code initializes three types representing the colors: red, green and blue. type ColorType = [string, number, number, number]; let red: ColorType = ['Red', 1, 0, 0]; let green: [string, number, number, number] = ['Green', 0, 1, 0]; let blue = ['Blue', 0, 0, 1];
The most common way to specify colors in CSS is to use their hexadecimal (or hex) values. Hex values are actually just a different way to represent RGB values. Instead of using three numbers between 0 and 255, you use six hexadecimal numbers. Hex numbers can be 0-9 and A-F.
There was a proposal for a type of string which matches a pattern (regex or something else), but that proposal haven't come to fruition yet.
As a result, what you ask for is unfortunately impossible as of TypeScript 2.2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With