Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create an array of strings from a type/interface keys?

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?

like image 226
saibbyweb Avatar asked Jun 02 '26 19:06

saibbyweb


1 Answers

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

like image 115
ZecKa Avatar answered Jun 05 '26 08:06

ZecKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!