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

如何用TypeScript限制字符串仅包含自定义类型的键名?

实现TypeScript字符串类型校验:仅允许包含指定对象键的空格分隔字符串

我们需要定义一个类型替代示例中的any,让TypeScript自动校验字符串是否仅包含目标对象的键(以空格分隔),空串或包含非目标键的字符串会触发类型错误。

解决方案代码

type Dog = {
  id: string
  breed: string
} 

type Fields<T> = keyof T & string;

// 替换any的核心类型定义
type StrWithFields<T> = 
  // 单个键的合法情况
  Fields<T> | 
  // 递归生成多键空格分隔的合法组合(支持任意顺序)
  { [K in Fields<T>]: `${K} ${StrWithFields<Omit<T, K>>}` }[Fields<T>];

// 针对Dog类型生成具体的校验类型
type DogStrWithFields = StrWithFields<Dog>;

// 合法赋值 - 全部通过校验
const a: DogStrWithFields = 'id';
const b: DogStrWithFields = 'breed';
const c: DogStrWithFields = 'id breed';
const d: DogStrWithFields = 'breed id';

// 非法赋值 - 均触发TypeScript类型错误
const e: DogStrWithFields = '';
const f: DogStrWithFields = 'id breed created_at';

类型工作原理

  1. Fields<T>:提取目标对象T的所有键,并确保类型为字符串(排除可能的symbol键);
  2. StrWithFields<T>:
    • 首先包含单个键的合法字符串(即Fields<T>的联合类型);
    • 通过映射类型+递归,对每个键K生成${K} ${StrWithFields<Omit<T, K>>}格式的字符串——也就是当前键后跟随空格,再加上剩余键的合法组合;
    • 最后通过索引访问[Fields<T>]将映射类型转换为联合类型,得到所有多键排列的合法字符串。

这个类型会自动枚举所有符合要求的字符串组合,只要赋值的字符串不在这个组合内,TypeScript就会抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:52:32