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

TypeScript:如何让const字符串数组参数支持带数量的合法水果取值?

TypeScript实现带数量的合法水果参数校验

我定义了如下数组和函数:

const PossibleFruits = [
  "apples",
  "bananas",
  "pears"
] as const

export const getFruits = (fruits: typeof PossibleFruits[number]) => {
  console.log(fruits);
}

当前调用情况:

const apple = getFruits("apples"); // 输出 "apples"
const pear = getFruits("pears"); // 输出 "pears"
const plum = getFruits("plums"); // 编译错误 ✅

现在我希望函数参数支持带数量的形式,允许以下合法调用:

const twoApples = getFruits("two apples"); // 应输出 "two apples"
const eightPears = getFruits("eight pears"); // 应输出 "eight pears"

同时,对于不合法的水果种类,调用时要触发编译错误:

const threePlums = getFruits("three plums"); // 期望触发编译错误

请问能否通过TypeScript的特性实现这一需求?


可以实现,核心是利用TypeScript的模板字面量类型结合原有的常量数组类型,生成支持数量前缀的合法参数类型。

完整实现代码

const PossibleFruits = [
  "apples",
  "bananas",
  "pears"
] as const;

// 可选:如果需要限制数量前缀,定义允许的前缀列表
type QuantityPrefix = "two" | "eight" | "three" | "one" | "five";

// 生成合法输入类型:纯水果名 或 「数量前缀 + 空格 + 水果名」
type ValidFruitInput = 
  | typeof PossibleFruits[number] 
  | `${QuantityPrefix} ${typeof PossibleFruits[number]}`;

// 也可以不限制前缀,允许任意字符串前缀:
// type ValidFruitInput = typeof PossibleFruits[number] | `${string} ${typeof PossibleFruits[number]}`;

export const getFruits = (fruits: ValidFruitInput) => {
  console.log(fruits);
};

// 合法调用示例
const apple = getFruits("apples");
const twoApples = getFruits("two apples");
const eightPears = getFruits("eight pears");

// 编译错误:plums不属于合法水果种类
const threePlums = getFruits("three plums"); 
// 若限制了前缀,下面这种也会报错:"ten"不在QuantityPrefix中
// const tenBananas = getFruits("ten bananas"); 

关键说明

  • 模板字面量类型${QuantityPrefix} ${typeof PossibleFruits[number]}会自动遍历所有合法水果和前缀的组合,生成对应的字符串联合类型。
  • 保留原有的typeof PossibleFruits[number]类型,兼容不带数量前缀的旧调用方式。
  • 原代码中export getFruits存在语法错误,已修正为export const getFruits。

内容的提问来源于stack exchange,提问作者user15951701

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:35:27