3

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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.