TypeScript实现:限制函数参数为对象数组Name属性的取值
解决方案
要实现让functionName参数只能接收data数组中Name属性的合法取值,你可以利用TypeScript的字面量类型推导和const断言来实现:
提取
data数组中Name属性的联合类型
因为你已经给data加上了as const断言,TypeScript会保留每个元素的字面量类型,此时可以通过typeof data[number]['Name']提取所有Name值的联合类型。将函数参数类型指定为这个联合类型
把getSystemInfo的functionName参数类型从string替换为上面提取的联合类型,这样TypeScript就会在编译时校验传入的值是否合法。
修改后的完整代码:
const data = [{ Name: 'functionA', EntryPoint: false, SystemOrClient: 'Client' }, { Name: 'functionB', EntryPoint: false, SystemOrClient: 'Client' }, { Name: 'functionC', EntryPoint: false, SystemOrClient: 'System' }] as const; // 提取Name属性的联合类型 type ValidFunctionName = typeof data[number]['Name']; const getSystemInfo = (functionName: ValidFunctionName) => { // ...你的业务逻辑 } getSystemInfo('functionA') // 编译通过 getSystemInfo('functionAB') // 编译报错:类型“"functionAB"”的参数不能赋给类型“"functionA" | "functionB" | "functionC"”的参数
这样修改后,只要传入的functionName不在data的Name取值范围内,TypeScript就会在编译阶段直接抛出错误,完全符合你的需求。
内容的提问来源于stack exchange,提问作者arunmmanoharan
相关产品推荐
相关产品推荐

