'React Typescript: Reflection (listing properties of an interface)
im writing a node-based editor for neural-nets that (currently) uses tensorflow.js for the creation of the networks themself. Tensorflow.js has a layers api with diffrent factory-functions that each have an interface for their arguments. E.g.
interface DenseLayerArgs {
units: number,
useBias?: boolean,
...
}
const dense(args: DenseLayerArgs): {
...
}
My goal is to load all of those factory functions automaticly and create a menu for each thats based on the Args interface. Since its not possible to access properties that might be undefined in plain TS, the solution seems to be some kind of transformer library (eg. https://www.npmjs.com/package/ts-reflection ). But i havnt been able to get any custom transformer running with my create-react-app with typescript setup.
Has anyone been able to get React working with custom transformers or has some other solution for creating a menu from an interface ?
cheers
Solution 1:[1]
I recommend the tst-reflect for the TypeScript Reflection.
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"
}
})
And how to list the properties of an Interface with tst-reflect?
import { getType, Property} from "tst-reflect";
interface DenseLayerArgs {
units: number,
useBias?: boolean,
// ...
}
const properties: Array<Property> = getType<DenseLayerArgs>().getProperties();
// Do something with properties...
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 |
