1

Suppose there's type or interface named NumberLookupCriteria:

type NumberLookupCriteria = {
  dialCode: string;
  phoneNumber: string;
}

or

interface NumberLookupCriteria {
  dialCode: string;
  phoneNumber: string;
}

Can we somehow manage to get all the keys as an JS array of strings like this:

const keys = ['dialCode','phoneNumber']

Any idea?

saibbyweb
  • 2,864
  • 2
  • 27
  • 48

1 Answers1

1

No you can't because types and interfaces doesn't exists at runtime.

A workaround can be the use of class

View ts playground

class NumberLookupCriteria {
    constructor(
        readonly dialCode: string ="",
        readonly phoneNumber: string ="",
    ) {}
}

const arrayKey = (Object.keys(new NumberLookupCriteria()))

console.log(arrayKey) // ["dialCode", "phoneNumber"]

const test: NumberLookupCriteria = {
  dialCode: "a",
  phoneNumber: "b"
} 
// OK

const test: NumberLookupCriteria = {
  dialCode: "a"
} 
// KO: Property 'phoneNumber' is missing in type '{ dialCode: string; }' but required in type 'NumberLookupCriteria'

There is many post about it:

Get keys of a Typescript interface as array of strings
Get Type keys in TypeScript

ZecKa
  • 2,552
  • 2
  • 21
  • 39