Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

 class Test { 
      propA;
      propB;
      propC;

   getSomeKeys() : keyof Test[] {
     return ['propA', 'propC']
   }
 }
like image 272
undefined Avatar asked Dec 20 '17 08:12

undefined


2 Answers

You need to wrap the keyof Test in brackets:

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

Note though, that keyof also includes getSomeKeys in this case.

like image 115
Lusito Avatar answered Sep 18 '22 20:09

Lusito


Use Array<keyof Test>:

class Test {
    propA;
    propB;
    propC;

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

demo

like image 28
tony19 Avatar answered Sep 20 '22 20:09

tony19