How to determine type for css color in TypeScript?

I have the following 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 am trying to get a build error if the color is not valid, for example:

var badge = Badge({
    color: 'rgba(100, 100, 100)',
    text: 'Danger'
});

Is there a way to define Colorso that it only allows strings matching one of the following patterns?

  • #FFF
  • #FFFFFF
  • rgb(5, 5, 5)
  • rgba(5, 5, 5, 1)
  • hsa(5, 5, 5)

I understand that there are such colors as redand white, but this can make the answer difficult if I Colorcan accept them.

+6
source share
2 answers

A string type was suggested that matches the pattern (regular expression or something else), but this sentence has not arrived yet.

, , TypeScript 2.2.

+7

, , :

type Color = "#FFFFFF" | "#FF0000" | "#0000FF";
const WHITE: Color = "#FFFFFF";
const RED: Color = "#FF0000";
const BLUE: Color = "#0000FF";

, , , , , .

script colors.css, CSS:

:root {
  --primary-red: #ff0000;
  --secondary-red: #993333;
  /* etc */
}

:

export const primaryRed: Color = "#ff0000";
export const secondaryRed: Color = "#993333";
// etc
export type Color = "#ff0000" | "#993333" // | etc...

:

import {primaryRed} from "./Colors.ts";

interface BadgeProps {
    color: Color;
    text: string;
}  

var badge = Badge({
    color: primaryRed,
    text: 'Danger'
});
+3

Source: https://habr.com/ru/post/1015450/


All Articles