【问题标题】:Concatenate string combinations in typescript在打字稿中连接字符串组合
【发布时间】:2023-01-19 23:40:36
【问题描述】:

我有很多(顺风)颜色字符串,我想将我的类型系统限制为。出于演示目的,我只在此处显示 3*3:

text-red-500    text-red-700    text-red-900
text-amber-500  text-amber-700  text-amber-900
text-yellow-500 text-yellow-700 text-yellow-900

我想做类似的事情:

type Color = "red" | "amber" | "yellow"
type Tint = "500" | "700" | "900"
type TailwindColor = "text-" + Color + "-" + Tint

我有办法在 Typescript 中执行此操作吗?

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    您可以使用模板字符串类型:

    type Color = "red" | "amber" | "yellow"
    type Tint = "500" | "700" | "900"
    type TailwindColor = `text-${Color}-${Tint}`
    

    Playground Link

    你应该小心,虽然这样的组合联合会变得很大,但它们往往会减慢编译器的速度,并且 TypeScript 允许的联合的最大大小是有限制的(不确定它是什么,但有一个硬​​性限制, ex)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 2016-05-28
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多