簡體   English   中英

如何使用 typescript compile api 生成裝飾器

[英]how to use generate a Decorator by typescript compile api

我想生成一個類,它的成員有多個“類驗證器”裝飾器來檢查屬性的類型。 我想我可以使用 ts.factory.createDecorator 來做到這一點,但我怎樣才能得到一個 ts.Expression?

找到這個,檢查也許對你有幫助

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM