typescript - 如何键入一个打字稿函数,该函数将对象数组作为第一个参数,并将对象上预期的特定属性作为参数?
问题描述
我有一个函数sortObjectsByDate( objects:any[], prop:string )
,我想使用prop
参数来指定存储在数组中的对象的哪个属性将用于排序,我想使用类型检查,因此该sortObjectsByDate
函数只接受具有该prop
属性的对象数组类型为 Date 对象。
如果我调用[ {foo: new Date() }]
作为第一个参数传递的函数并"foo"
作为第二个参数传递,我希望没有类型错误......
[ {bar: new Date(), foo: "nope" }]
但是如果我作为第一个参数和第二个参数传递,我想要一个类型错误,"foo"
因为[ {bar: new Date(),foo: "nope" }]
没有一个foo
属性是Date
.
解决方案
给你:游乐场链接
function sortObjectsByDate
<K extends string, T extends { [key in K]: Date }>
(objects: T[], prop: K)
{
// ...
}
每当您需要在类型之间关联某些内容时,您都需要使用泛型参数。这K
是密钥字符串,然后T
可以是任何具有K: Date
.
// Works:
sortObjectsByDate([ { bar: new Date() } ], "bar");
// Error: Type 'string' is not assignable to type 'Date'.(2322)
sortObjectsByDate([ { bar: new Date(), foo: "nope" } ], "foo");
推荐阅读
- c++ - 如何在 ubuntu 中获取 Qt PostgreSQL 插件?
- python-3.x - 如何将pytorch张量中的元素映射到id?
- python-3.x - pygame中22x16网格中的正方形顶点
- c - 序列化是什么意思以及为什么它与 socket.s 一起使用时性能更好
- java - 基于Java中的关键属性从哈希图中删除对象
- python - 通过程序将文件导入python程序
- r - 使用许多观察值更改散点图点颜色
- javascript - 具有联合类型的 Typescript 通用接口
- javascript - SVG 形状内的图像溢出笔划
- splunk - Splunk企业默认密码是多少