You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建由空格分隔多个Format类型的TypeScript类型?

TypeScript实现任意数量带/不带px后缀数字的空格拼接类型

需求说明

需要实现一个类型,允许用空格拼接**任意数量(或最多12个)**的带/不带px后缀的数字字符串。当前代码仅支持两个元素的拼接,希望优化实现。

TypeScript版本:4.9.5

原代码:

export type Format = `${number}` | `${number}px`;

// 仅支持两个元素的拼接
export type Input = `${Format} ${Format}`;

期望合法示例:

const input: Input = '1';
const input: Input = '1 2';
const input: Input = '1 2 3';
const input: Input = '1 2 10px';
const input: Input = '10px 1 2 20px';
// 更多类似组合均需合法

解决方案

1. 实现任意数量元素的拼接(递归方式)

利用TypeScript 4.5+支持的递归模板字符串特性,可直接定义递归类型,支持任意数量的Format元素拼接(受限于TS默认递归深度限制,一般场景完全够用):

export type Format = `${number}` | `${number}px`;

// 支持单个元素,或单个元素+空格+任意数量的元素组合
export type Input = Format | `${Format} ${Input}`;

2. 实现最多12个元素的拼接(递归计数方式)

如果需要限制最大数量(比如最多12个),可以通过带计数的递归辅助类型实现,避免逐个枚举:

export type Format = `${number}` | `${number}px`;

// 辅助类型:递归拼接,同时跟踪当前元素数量,直到达到最大限制
type InputWithMax<Max extends number, Count extends number[] = []> = 
  Count['length'] extends Max 
    ? never // 达到最大数量后停止
    : Format | `${Format} ${InputWithMax<Max, [...Count, 0]>}`;

// 最多支持12个元素的Input类型
export type Input = InputWithMax<12>;

验证说明

上述两种实现均可满足示例中的所有合法场景:单个元素、多个元素混合带/不带px后缀的组合都会被TypeScript正确识别为合法类型。

内容的提问来源于stack exchange,提问作者Get Off My Lawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:17:12