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

如何基于TypeScript对象类型生成包含所有键的常量数组约束类型

TypeScript 数组与对象键完全匹配的类型定义

实现方案

推荐方案:泛型工厂函数

该方案使用简单,类型报错清晰,适配绝大多数场景:

type Fields = {
  countryCode: string;
  currency: string;
  otherFields: string;
};

function defineAllowedFields<T extends readonly (keyof Fields)[]>(
  fields: keyof Fields extends T[number] ? T : never
) {
  return fields;
}

校验效果

// 符合规则:包含所有Fields键、无额外字段
const allowedFields = defineAllowedFields(["countryCode", "currency", "otherFields"] as const);

// 触发类型错误:缺少Fields的部分键
const allowedFields1 = defineAllowedFields(["countryCode"] as const);

// 触发类型错误:包含Fields不存在的额外字段
const allowedFields2 = defineAllowedFields(["countryCode", "currency", "otherFields", "extraField"] as const);

纯类型定义方案

如果你需要直接声明SomeType类型,可以使用如下写法:

type FieldKeys = keyof Fields;
type SomeType = readonly FieldKeys[] & (FieldKeys extends (typeof allowedFields)[number] ? typeof allowedFields : never);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:09:04