Home > OS >  Select property name from object in typescript via interface
Select property name from object in typescript via interface

Time:03-15

Let's say I have a simplyfied code like this:

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"

I'm accessing the property from a base class via the string "property" from MyInterface. This only works because I only allow it to be "name" excactly.

I want to specify the property-property to only allow strings that represent properties on the generic object T. If I just change it to "string" Typescript will complain in myFunc of course and I do not want to explicitely cast to any or something.

Is this possible?

regards and thanks in advance, Christoph

CodePudding user response:

You could use keyof. I slightly modified your code below:

interface MyBase {
  name: string;
}

interface MyInterface<T extends MyBase> {
  base: T;
  age: number;
  property: keyof T; // 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));
  • Related