0

I have an interface defined and has multiple properties. Is there a way that I could read the property names in typescript/angular.

My interface looks is something similar as below

    export interface InterfaceName
   {
     property1: string;
     property2: string;
     property3: number;
   }
Abhishek
  • 23
  • 2
  • There is a hacky way - check out this: https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-strings – Aviad P. Aug 09 '21 at 18:43

1 Answers1

0

I recommend the tst-reflect for the TypeScript Reflection.

I've made you this StackBlitz demo.

How to list the properties of an Interface with tst-reflect?

import { getType, Property} from "tst-reflect";

interface InterfaceName
{
    property1: string;
    property2: string;
    property3: number;
}

const properties: Array<Property> = getType<InterfaceName>().getProperties();
// Do something with properties...

TL;DR;

In the README, there is a section How to Start. You have to use eg. ttypescript to get transformers working. TypeScript does not support transformers out of the box, only by direct calls to their Compiler API. ttypescript is some kind of wrap which allows you to define transformers in tsconfig.

Copy of that How to Start:

  1. Install packages.
npm i tst-reflect && npm i tst-reflect-transformer -D
  1. In order to use transformer plugin you need TypeScript compiler which supports plugins eg. package ttypescript or you can use TypeScript compiler API manually.
npm i ttypescript -D
  1. Add transformer to tsconfig.json
{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    }
}
  1. Now just transpile your code by ttsc instead of tsc
npx ttsc

And usage with Webpack:

Modify your webpack config. Use options.compiler of ts-loader to set ttypescript compiler.

({
    test: /\.(ts|tsx)$/,
    loader: require.resolve("ts-loader"),
    options: {
        compiler: "ttypescript"
    }
})

Property is:

interface Property
{
    /**
     * Property name
     */
    readonly name: string;
    /**
     * Property type
     */
    readonly type: Type;
    /**
     * Optional property
     */
    readonly optional: boolean;
    /**
     * Access modifier
     */
    readonly accessModifier: AccessModifier;
    /**
     * Accessor
     */
    readonly accessor: Accessor;
    /**
     * Readonly
     */
    readonly readonly: boolean;
    /**
     * Returns array of decorators
     */
    getDecorators(): ReadonlyArray<Decorator>;
}
Hookyns
  • 159
  • 1
  • 4