TypeScript定义:如何在对象中限定数组属性仅接受特定字符串
Hey!看起来你想要给对象的communicationPreferences数组限定只能用特定的字符串值对吧?我给你分TypeScript和纯JavaScript两种场景来解决,都是很实用的方案~
TypeScript 实现(类型安全首选)
如果你用TypeScript的话,直接通过联合类型或者枚举就能在编译阶段就把非法值拦下来,非常省心:
方案1:联合类型
先定义允许的通信方式的联合类型,再用它约束数组:
// 限定所有允许的通信方式 type CommunicationMethod = 'email' | 'whatsApp' | 'weChat' | 'skype' | 'line' | 'sms'; // 定义User对象的类型结构 type User = { name: string; communicationPreferences: CommunicationMethod[]; }; // 合法的使用示例 const user1: User = { name: 'John', communicationPreferences: ['email', 'whatsApp'] // ✅ 完全符合要求 }; const user2: User = { name: 'John', communicationPreferences: ['whatsApp', 'weChat', 'skype'] // ✅ 没问题 }; // 非法值会直接在编译时报错 const invalidUser: User = { name: 'John', communicationPreferences: ['email', 'telegram'] // ❌ 报错:'telegram'不在允许的类型范围内 };
方案2:枚举类型
如果希望代码可读性更强,也可以用枚举来定义允许的值:
enum CommunicationMethod { Email = 'email', WhatsApp = 'whatsApp', WeChat = 'weChat', Skype = 'skype', Line = 'line', Sms = 'sms' } type User = { name: string; communicationPreferences: CommunicationMethod[]; }; // 使用枚举值来赋值,更直观 const user: User = { name: 'John', communicationPreferences: [CommunicationMethod.Email, CommunicationMethod.WhatsApp] };
JavaScript 运行时校验
如果只能用纯JavaScript,没有TypeScript的类型检查,那我们可以写个简单的校验函数,在运行时确保数组里的每个值都合法:
// 先定义所有允许的通信方式,用Set来做快速查找 const ALLOWED_COMM_METHODS = new Set(['email', 'whatsApp', 'weChat', 'skype', 'line', 'sms']); // 校验函数:检查数组是否合法 function isValidCommunicationPreferences(prefs) { // 先确保是数组 if (!Array.isArray(prefs)) return false; // 检查每个元素都在允许的集合里 return prefs.every(pref => ALLOWED_COMM_METHODS.has(pref)); } // 封装一个创建用户的函数,自带校验 function createUser(name, communicationPreferences) { if (!isValidCommunicationPreferences(communicationPreferences)) { throw new Error('communicationPreferences包含不允许的通信方式!'); } return { name, communicationPreferences }; } // 合法使用 const user1 = createUser('John', ['email', 'whatsApp']); const user2 = createUser('John', ['whatsApp', 'weChat', 'skype']); // 非法使用会抛出错误 try { const invalidUser = createUser('John', ['email', 'telegram']); } catch (e) { console.error(e.message); // 输出:communicationPreferences包含不允许的通信方式! }
如果担心ALLOWED_COMM_METHODS被意外修改,可以用Object.freeze把它冻结:
const ALLOWED_COMM_METHODS = Object.freeze(new Set(['email', 'whatsApp', 'weChat', 'skype', 'line', 'sms']));
内容的提问来源于stack exchange,提问作者Wei-jye
相关产品推荐
相关产品推荐

