0

I'm sorry for the bad title, I'm not sure how to describe the situation and maybe that's why I still haven't found the solution

i have an interface

interface Fields {
  name: string
  age: number
}

and I would like to extract the keys to create a type, for example

type FieldList = ?

// expected result
// type FieldList = 'name' | 'age'

and at another time I would like to use the extracted type to create an array

const list: FieldList = ['name', 'age']

TS Playground

Yung Silva
  • 1,324
  • 4
  • 20
  • 40
  • Does this answer your question? [Get keys of a Typescript interface as array of strings](https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-strings) – pilchard May 28 '21 at 20:59
  • You need union type from another Interface `type FieldsKeys = keyof Fields;` `type FieldList = FieldsKeys[];` Check [this](https://www.typescriptlang.org/play?#code/C4TwDgpgBAYglhANgEwM5QLxQN4FgBQUUAdgIYC2EAXFKsAE5zEDmBRpz1JAruQEYR6BAL4ECoSLAQoAMnDqYoACgDWEEAHsAZlKRoAlAG0AugQD0ZqBOjw9chVgDkZSo6gAfKI44RHY-ADGGsQKiPLANLay4YqGAEQuEHEANFBxPilpqBqUwAAWTMxxpvgEQA) – Akhil May 28 '21 at 21:06
  • @pilchard no, it's not what i need. – Yung Silva May 28 '21 at 21:20
  • It had all the same info as the answer you accepted. – pilchard May 28 '21 at 21:20

1 Answers1

0

I see two questions (or perhaps three).

How to get the keys of a type?

type FieldList = keyof Fields;

FieldList is now a string literal union'name' | 'age';

How to get an array containing the keys of a type?

That's not possible – you can't "materialize" a type into a value.

How to get an array type which can only contain keys of another type?

That's just FieldList[].

const list: FieldList[] = ['name', 'age']; // ok

const badList: FieldList[] = ['address']; // error
rsmeral
  • 518
  • 3
  • 8
  • the third answer is what i need, `get an array type which can only contain keys of another type`, but would there be any way to define this in just a single line? because this is a function parameter, [example](https://i.ibb.co/G5Gk01J/Captura-de-Tela-2021-05-28-a-s-18-14-20.png) – Yung Silva May 28 '21 at 21:15
  • What do you mean by _in just a single line_? From the example, I understand that you can call `removeErrors(['age', 'name'])`. – rsmeral May 28 '21 at 21:18
  • 1
    `Array` works fine, do you see anything better? – Yung Silva May 28 '21 at 21:19
  • thanks for all the help, [here is the final result](https://tsplay.dev/NVnxxN) – Yung Silva May 28 '21 at 21:21