Consider a simplified code snippet like the following:
interface MyBase {
name: string;
}
interface MyInterface<T extends MyBase> {
base: MyBase;
age: number;
property: "name" // should be: "string" but only properties from T
}
const myFunc = <T extends MyBase>(item: MyInterface<T>) => {
return item.base[item.property];
}
let t:MyInterface<MyBase> = {base: {name: "Chris"}, age: 30, property: "name"};
console.log(myFunc(t)); // will log "Chris"
The code above demonstrates accessing a property from a base class using the string "property" from MyInterface. This approach works because it is specifically limited to being just "name."
What I want to accomplish is restricting the property to only allow strings representing properties on the generic object T. If I were to change it to just "string," Typescript would understandably raise an error in myFunc, and I'd prefer not to resort to explicitly casting to any.
Is there a way to achieve this alternative constraint?
Thanks in advance, Christoph