How can I define a type for a CSS color in TypeScript

0 votes

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.

Jun 14 in TypeSript by Logan
• 2,140 points
11 views

1 answer to this question.

0 votes

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.

answered Jun 15 by Nina
• 3,020 points

Related Questions In TypeSript

0 votes
1 answer

How to define props in TypeScript where a parent component injects props in its children?

Typescript doesn't remove this special rule "!text" ...READ MORE

answered Jun 16 in TypeSript by Nina
• 3,020 points
70 views
0 votes
0 answers

What is a type in Typescript for the Component class in Angular 2+?

I have a small problem, but big ...READ MORE

Jul 5 in TypeSript by Logan
• 2,140 points
12 views
0 votes
0 answers

How can I include pug templates in compiled typescript?

My nodejs based application uses Pug for ...READ MORE

Jul 13 in TypeSript by Logan
• 2,140 points
36 views
0 votes
0 answers

How can I create a navigational compass using Typescript and HTML?

I'm looking to display a compass heading ...READ MORE

Jul 13 in TypeSript by Logan
• 2,140 points
22 views
0 votes
1 answer

How to install and run Typescript locally in npm?

It took me a while to figure ...READ MORE

answered Jun 8 in TypeSript by Nina
• 3,020 points
175 views
0 votes
1 answer

Cannot access web3 object with typescript and ethereum

You still need to instantiate it first. ...READ MORE

answered Sep 25, 2018 in Blockchain by slayer
• 29,310 points
1,857 views
0 votes
1 answer

How to apply zoom animation for each element of a list in angular?

Hey @Sid, do check if this link ...READ MORE

answered Jul 30, 2019 in Others by Vardhan
• 13,200 points
511 views
0 votes
1 answer

How do I extend a TypeScript class definition in a separate definition file?

If you don't have control over the ...READ MORE

answered Jun 10 in TypeSript by Nina
• 3,020 points
153 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP