如何用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';
类型工作原理
Fields<T>:提取目标对象T的所有键,并确保类型为字符串(排除可能的symbol键);StrWithFields<T>:- 首先包含单个键的合法字符串(即
Fields<T>的联合类型); - 通过映射类型+递归,对每个键
K生成${K} ${StrWithFields<Omit<T, K>>}格式的字符串——也就是当前键后跟随空格,再加上剩余键的合法组合; - 最后通过索引访问
[Fields<T>]将映射类型转换为联合类型,得到所有多键排列的合法字符串。
- 首先包含单个键的合法字符串(即
这个类型会自动枚举所有符合要求的字符串组合,只要赋值的字符串不在这个组合内,TypeScript就会抛出错误。
内容的提问来源于stack exchange,提问作者Pavel Perevezencev
相关产品推荐
相关产品推荐

