Get Keys of a Type using Keyof Type Operator

Viewed 1357

I have this Identity interface

export interface Identity {
    username: string;
    name: string;
    surname: string;
    roles: string[];
}

and I want to get an array of Strings at runtime with all its keys.

const keys: string[] = ["username", "name", "surname", "roles"];

If it were a class, it would have been easy enough using the constructor (as suggested here).

class Identity {
    constructor(
        readonly username?: string,
        readonly name?: string,
        readonly surname?: string,
        readonly roles?: string[]
    ) {}
}

const properties: string[] = Object.keys(new Identity());

I have found other similar questions, some about the Keyof Type Operator, with the most relevant being:

In the above questions, however, the result of keyof is only used as a type/value constraint. What about how to get the keys as a String array using the keyof operator? Is this not possible from an Interface definition or for classes too?

TypeScript Custom Transformer

This project, a custom transformer, does exactly what I'm looking for: get the keys of a given Type.

I'm wondering if there is an easier way, possibly using only the keyof operator to get the same result.

0 Answers
Related