我推荐 tst-reflect 用于 TypeScript 反射。
在 README 中有一段 How to Start。你必须使用例如。 ttypescript 让变压器工作。 TypeScript 不支持开箱即用的转换器,只能通过直接调用它们的 Compiler API 来支持。 ttypescript 是某种包装,允许您在 tsconfig 中定义转换器。
如何开始的副本:
- 安装包。
npm i tst-reflect && npm i tst-reflect-transformer -D
- 为了使用转换器插件,您需要支持插件的 TypeScript 编译器,例如。打包ttypescript 或者你可以手动使用TypeScript compiler API。
npm i ttypescript -D
- 将变压器添加到
tsconfig.json
{
"compilerOptions": {
// your options...
// ADD THIS!
"plugins": [
{
"transform": "tst-reflect-transformer"
}
]
}
}
- 现在只需使用
ttsc 而不是 tsc 转换您的代码
npx ttsc
和 Webpack 的用法:
修改你的 webpack 配置。使用options.compiler 的ts-loader 设置ttypescript 编译器。
({
test: /\.(ts|tsx)$/,
loader: require.resolve("ts-loader"),
options: {
compiler: "ttypescript"
}
})
以及如何用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 是:
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>;
}