首页 > 解决方案 > 如何键入一个打字稿函数,该函数将对象数组作为第一个参数,并将对象上预期的特定属性作为参数?

问题描述

我有一个函数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.

标签: typescripttypescript-generics

解决方案


给你:游乐场链接

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");

推荐阅读