[英]how to use generate a Decorator by typescript compile api
I want to generate a class whose members has more than one 'class-validator' Decorator to check the type of property.我想生成一个类,它的成员有多个“类验证器”装饰器来检查属性的类型。 I think i can use ts.factory.createDecorator to do that, but how can i get a ts.Expression?
我想我可以使用 ts.factory.createDecorator 来做到这一点,但我怎样才能得到一个 ts.Expression?
found this, check maybe will be helpfull for you找到这个,检查也许对你有帮助
/* output
@niceDecorator(“bar”)
class foo {
}
*/
const p = ts.createIdentifier(‘niceDecorator’);
const call = ts.createCall(p, undefined, [str]);
const dec = ts.createDecorator(call);
const classDec = ts.createClassDeclaration([dec], undefined, ‘foo’, undefined, undefined, undefined);
I'm trying to do the same, couldn't find how to make it.我正在尝试做同样的事情,找不到如何制作它。
as for code example (which is not working):至于代码示例(不起作用):
const newMembers = node.members.map(propertyNode => {
if(ts.isPropertyDeclaration(propertyNode)) {
const newDecorators = [...propertyNode.decorators];
if (propertyNode.type.kind === 149) {
// STRING ts.SyntaxKind[kind]
const newExpression = ts.factory.createDecorator(
{
_expressionBrand: 'IsString',
}
)
newDecorators.push({
kind: ts.SyntaxKind.Decorator,
parent: propertyNode,
expression: newExpression,
});
}
const updRes = ts.factory.updatePropertyDeclaration(
propertyNode,
newDecorators,
propertyNode.modifiers,
propertyNode.name,
undefined,
propertyNode.type,
propertyNode.initializer
)
return updRes;
}
const updClassRes = ts.factory.updateClassDeclaration(
node,
node.decorators,
node.modifiers,
node.name,
node.typeParameters,
node.heritageClauses,
newMembers
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.