In search of defining a versatile interface that can manage any Data
type, I came up with an idea. This interface includes a dataKey
property which simply holds a value of keyof Data
. Additionally, it features a handler function where the parameter type should align with the type retrieved when using dataKey
to access a value from Data
. The concept is outlined below, although it fails as Data[dataKey]
isn't valid in TypeScript:
interface Handler<Data> {
dataKey: keyof Data,
handler: (value: Data[dataKey]) => void
}
Is there a method to make this approach operational? Substituting Data[dataKey]
with the any
type might seem like a quick fix, but it sacrifices type safety.
Below exemplifies how I envision utilizing the Handler
interface:
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 are certain about the type of `value` being string,
// derived from accessing `name` within the person object.
// Changing the dataKey to "age" should result in
// the type of `value` being `number`, respectively
console.log("Name:", value);
}}
handleData(person, handler);