简体   繁体   English

Typescript keyof返回字符串数组

[英]Typescript keyof return array of strings

Let's say I have a class: 假设我有一节课:

class Test { 
  propA;
  propB;
  propC;
}

I want to create a method that returns an array of strings and type it to be only the keys existing in the Test class, how can I do this with the keyof feature? 我想创建一个返回字符串数组的方法,并将其键入为Test类中现有的键,如何使用keyof功能执行此keyof

 class Test { 
      propA;
      propB;
      propC;

   getSomeKeys() : keyof Test[] {
     return ['propA', 'propC']
   }
 }

You need to wrap the keyof Test in brackets: 您需要将keyof Test包装在括号中:

 class Test { 
   //...
   getSomeKeys() : (keyof Test)[] {
     return ['propA', 'propC']
   }
 }

Note though, that keyof also includes getSomeKeys in this case. 但请注意,在这种情况下,keyof还包括getSomeKeys。

Use Array<keyof Test> : 使用Array<keyof Test>

class Test {
    propA;
    propB;
    propC;

    getSomeKeys(): Array<keyof Test> {
        return ['propC'];
    }
}

demo 演示

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

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