小编Wea*_*sel的帖子

寻找由模板文字类型的任何可能组合组成的 TypeScript 类型

对于我的项目,我需要提出一个 TypeScript 类型,这就是所谓的 CardSize。

这种类型可以采取多种形式。它可以是静态值、响应式(特定于断点的)值,也可以是由空格分隔的两者的组合。

可能的(奇异)值如下:

type CardSize =
'compact' |
'normal' |
'compact@small' |
'compact@medium' |
'compact@large' |
'normal@small' |
'normal@medium' |
'normal@large';
Run Code Online (Sandbox Code Playgroud)

我最终想要的类型如下:

type CardSize = 
'compact' | 
... |
'normal@large' |
'compact normal@medium' |
'compact compact@small normal@medium' | 
'compact@small normal@large' etc.
Run Code Online (Sandbox Code Playgroud)

第一步似乎是使用模板文字类型,因此我涵盖了所有单数类型:

type CardSize = Size | `${Size}@${Breakpoint}`;
Run Code Online (Sandbox Code Playgroud)

接下来,我尝试研究排列以获得可能值的任意组合,但到目前为止还没有运气。

如果我能以某种方式实现这两个约束,那就太好了:

将可能的组合数量限制为仅同时分配一个特定的断点值(例如,不在同一字符串中同时分配'compact@small'和)'normal@small

其次,如果排列顺序无关紧要就好了。我认为以下内容相同:

const size: CardSize = 'compact@small @normal@large';
const size: CardSize = 'normal@large compact@small';
Run Code Online (Sandbox Code Playgroud)

有人知道如何实现这种类型的排列吗?即使这意味着没有这两个限制,这也会有很大的帮助!

回复:我意识到排列类型对于我想要实现的目标来说有点矫枉过正。CardSize我可以在不依赖| string作为后备的情况下强制执行类型安全吗?

typescript typescript-typings

5
推荐指数
1
解决办法
858
查看次数

标签 统计

typescript ×1

typescript-typings ×1