简体   繁体   English

Select property name 来自 object in typescript 通过接口

[英]Select property name from object in typescript via interface

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.我正在通过 MyInterface 中的字符串“属性”从基数 class 访问该属性。 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.我想指定 property-property 以仅允许表示通用 object T 上的属性的字符串。如果我只是将其更改为“字符串”,Typescript 当然会在 myFunc 中抱怨,我不想明确地强制转换为任何内容。

Is this possible?这可能吗?

regards and thanks in advance, Christoph提前问候和感谢,克里斯托夫

You could use keyof .你可以使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM