【发布时间】:2022-11-29 05:19:34
【问题描述】:
我想定义一个能够处理任何 Data 类型的通用接口。该接口有一个dataKey 属性,它的值只是一个keyof Data。它还有一个处理函数,它的参数类型应该和使用dataKey从Data读取一个值的类型相同。应该是这样的,但这不起作用,因为 Data[dataKey] 不是有效的 TypeScript:
interface Handler<Data> {
dataKey: keyof Data,
handler: (value: Data[dataKey]) => void
}
有没有办法让它工作?我可以使用 any 类型而不是 Data[dataKey],但这并不能保证类型安全。
这是我想如何使用 Handler 接口的示例:
function handleData<Data extends object>(data: Data, handler: Handler<Data>) {
const value = data[handler.dataKey];
handler.handler(value);
}
interface Person {
name: string,
age: number,
}
const person: Person = {name: "Seppo", age: 56};
const handler: Handler<Person> = {dataKey: "name", handler: (value: string) => {
// Here we know that the type of `value` is string,
// as it is the type of reading `name` from the person object.
// If I change dataKey to "age", the type of `value`
// should be `number`, respectively
console.log("Name:", value);
}}
handleData(person, handler);
【问题讨论】:
-
interface Handler<Data, K extends keyof Data = keyof Data> {- 然后在您的处理程序中使用Data[K]。 -
你不能真的用界面直接,但你可以创建一个以这种方式工作的联合类型。 Does this approach满足你的需求吗?如果是这样,我可以写一个答案来解释;如果没有,我错过了什么? (如果您回复,请通过@jcalz 联系我)
-
@caTS 我试过你的例子,但不幸的是我无法让它工作。你能告诉我一个有效的例子吗?
-
@jcalz 你的例子似乎有效,但我不太明白:D
-
@jcalz 我在我的应用程序代码中测试了您的解决方案,它可以正常工作。 :) 因此,如果您愿意,请随时写下答案/解释。 :)
标签: typescript typescript-typings typescript-generics