【问题标题】:how to use generate a Decorator by typescript compile api如何使用通过 typescript compile api 生成装饰器
【发布时间】:2021-09-08 14:53:08
【问题描述】:

我想生成一个类,其成员有多个“类验证器”装饰器来检查属性的类型。我想我可以使用 ts.factory.createDecorator 来做到这一点,但我怎样才能获得 ts.Expression?

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: typescript compilation


【解决方案1】:

找到这个,检查一下可能对你有帮助

/* 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);

我正在尝试做同样的事情,找不到方法。

至于代码示例(不起作用):

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
        )

【讨论】:

    猜你喜欢
    • 2022-08-15
    • 2019-07-23
    • 2018-06-08
    • 1970-01-01
    • 2019-03-09
    • 2014-12-26
    • 1970-01-01
    • 2020-03-04
    • 2022-01-09
    相关资源
    最近更新 更多