'Is there a way to read property names from interface in typescript similar to reflections in c#
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;
}
Solution 1:[1]
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:
- Install packages.
npm i tst-reflect && npm i tst-reflect-transformer -D
- 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
- Add transformer to
tsconfig.json
{
"compilerOptions": {
// your options...
// ADD THIS!
"plugins": [
{
"transform": "tst-reflect-transformer"
}
]
}
}
- Now just transpile your code by
ttscinstead oftsc
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>;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hookyns |
