Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a type for a css color in TypeScript?

Tags:

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.

like image 753
styfle Avatar asked Mar 03 '17 16:03

styfle


People also ask

How do you define a color type in TypeScript?

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

How do I specify CSS colors?

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.


1 Answers

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.

like image 121
Madara's Ghost Avatar answered Sep 20 '22 15:09

Madara's Ghost