TypeScript中泛型readRecords函数传递任意类型filter的类型定义问题
在TypeScript中实现支持任意类型filter的泛型readRecords()函数
嘿,我来帮你搞定这个TypeScript里的泛型函数写法~ 首先先回顾下你在AngularJS里的写法:
var filter = { 'order_type': 'new', 'city_id': 5 } readRecords(filter) function readRecords(filter){ }
在TypeScript里,确实需要指定类型,但根据你的需求(支持任意类型的filter),有几种合适的写法,我给你逐一说明:
1. 最基础的灵活写法:使用object类型
这种写法最简单,直接把filter的类型定义为object,能接受任意对象作为参数:
let filter = { 'order_type': 'new', 'city_id': 5 }; readRecords(filter); function readRecords(filter: object) { // 在这里处理filter逻辑 }
不过这种方式的缺点是,函数内部无法直接访问filter的属性(比如filter.order_type会报错),因为TypeScript不知道这个object具体有哪些属性。
2. 更明确的索引签名写法
如果你的filter总是以字符串作为键,值可以是任意类型,那可以用索引签名来定义:
let filter = { 'order_type': 'new', 'city_id': 5 }; readRecords(filter); function readRecords(filter: { [key: string]: any }) { // 现在可以安全访问filter的属性了 console.log(filter.order_type); }
这种写法既保留了灵活性,又能让TypeScript知道你可以通过字符串键访问filter的属性,适合大多数场景。
3. 泛型写法(推荐,类型更安全)
如果你希望readRecords函数能自动推导filter的具体类型,并且在函数内部能获得完整的类型提示,那泛型是最佳选择:
let filter = { 'order_type': 'new', 'city_id': 5 }; readRecords(filter); // 定义泛型函数,T代表filter的具体类型 function readRecords<T>(filter: T) { // 这里可以获得filter的完整类型提示,比如输入filter.会自动提示order_type和city_id console.log(filter.order_type); }
甚至你可以给泛型加个约束,确保filter是对象类型(避免传入非对象参数):
function readRecords<T extends object>(filter: T) { // 逻辑处理 }
这样不管你的filter是什么结构,TypeScript都能自动推导它的类型,同时保证类型安全,完美匹配你“传入任意类型filter”的需求~
内容的提问来源于stack exchange,提问作者Ashutosh
相关产品推荐
相关产品推荐

