如何根据动态参数名推断函数返回类型,实现类型安全调用?
实现带类型安全的getAccount包装器
可以通过泛型函数+字符串字面量数组推断来实现这个需求,核心是让TypeScript捕获传入数组的具体字符串字面量类型,而非宽泛的string[]。
步骤1:调整类型定义(可选,也可直接内联)
你之前的Obj类型可以调整为支持只读数组(适配更多场景):
type Obj<T extends readonly string[]> = { [K in T[number]]: string; };
步骤2:编写类型安全的包装器函数
用泛型约束限定输入参数为只读字符串数组,让TypeScript自动推断数组的具体元素类型:
// 模拟无类型的外部函数 declare function getAccount(keys: string[]): any; // 类型安全的包装器 function typedGetAccount<T extends readonly string[]>(keys: T): Obj<T> { // 调用原始函数并做类型断言(弥补原始函数无类型的缺陷) return getAccount(Array.from(keys)) as Obj<T>; }
使用示例
直接传入字面量数组时,TypeScript会自动推导返回对象的具体类型:
const res = typedGetAccount(['name', 'id']); // res的类型自动推导为 { name: string; id: string } res.name; // ✅ 类型安全,无报错 res.age; // ❌ TypeScript会报错:属性'age'不存在于类型'{ name: string; id: string }'
如果是传入变量数组,需要用as const让TypeScript保留字面量类型:
const accountKeys = ['name', 'id'] as const; const res = typedGetAccount(accountKeys); // 同样能得到 { name: string; id: string } 的类型
原理说明
- 泛型
T extends readonly string[]让TypeScript将传入的数组推断为具体的字符串字面量数组类型(比如['name','id']),而非宽泛的string[]。 - 映射类型
[K in T[number]]遍历数组的每个元素,生成对应的键值对类型。 - 类型断言
as Obj<T>是因为原始函数无类型声明,需要明确告诉TypeScript返回值符合我们定义的结构。
内容的提问来源于stack exchange,提问作者trixobird
相关产品推荐
相关产品推荐

