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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With