如何在 TypeScript 中为 css 颜色定义类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42584228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:18:34  来源:igfitidea点击:

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

typescripttypes

提问by styfle

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 Colorso that it allows only strings matching one of the following patterns?

有没有办法定义Color它只允许匹配以下模式之一的字符串?

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

I realize that there are colors like redand whitebut that might make this harder to answer if Colorcan accept those.

我意识到有像这样的颜色redwhite但是如果Color可以接受这些颜色,这可能会使这个问题更难回答。

回答by Madara's Ghost

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.

因此,不幸的是,从 TypeScript 2.2 开始,您所要求的内容是不可能的。

回答by Aaron Beall

You can't do this yet in a general sense, but you can use constants and string literal types if you have a well defined set of colors:

一般来说,您还不能这样做,但如果您有一组明确定义的颜色,则可以使用常量和字符串文字类型:

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

Obviously, this won't be practical if you want to allow anycolor, but in reality you probably dowant to have re-usable color variables anyway.

显然,如果您想允许任何颜色,这将不切实际,但实际上您可能确实希望拥有可重复使用的颜色变量。

In my project I use a script to generate a similar file from my colors.cssfile which defines a bunch of CSS properties:

在我的项目中,我使用一个脚本从我的colors.css文件中生成一个类似的文件,该文件定义了一堆 CSS 属性:

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

Which gets converted to:

转换为:

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

And I'd use it like:

我会像这样使用它:

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

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

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