打字稿反射 - 所需参数&默认值

时间:2016-01-09 18:11:44

标签: reflection typescript optional-parameters

简而言之:有没有办法知道是否需要打字稿参数和/或是否有默认值?

更长的版本: 说我有以下文件:

//Foo.ts
class Bar {
    foo(required:string,defaultValue:number=0,optional?:boolean) {
        ...
    }
}

我想知道每个参数:

  • 名称
  • 类型
  • 是必需的吗?
  • 是否有默认值?

我已成功使用method decoratorsTypeScript reflection API获取参数类型,我已使用this method获取其名称,但到目前为止我还没有找到了解变量是否必需和/或具有默认值的方法。

我知道打字稿编译器本身可以在打字稿中使用。所以我想知道是否有办法使用编译器的解析树来查看是否需要参数和/或是否有默认值?

那会怎么样?

1 个答案:

答案 0 :(得分:5)

如果您想从头开始......

从较高的层面来说,一种方法是:

  1. 了解如何使用文件的编译器api获取SourceFile节点。这本身就需要一些解释。
  2. 从那里,使用api的forEachChild函数循环遍历文件中的所有节点,找到kind SyntaxKind.ClassDeclaration和.name属性的节点文字Bar
  3. 然后再次使用api的forEachChild函数遍历该类的所有子项,并获取具有SyntaxKind.MethodDeclaration和.name属性的文本{{1} }。
  4. 要获取参数,您需要遍历方法节点的foo属性。
  5. 然后,对于每个参数节点,要获取名称,您可以在parameters属性上调用.getText()
  6. 您可以通过执行以下操作来判断参数是否可选:

    .name

    或者您可以使用const parameterDeclaration = parameterNode as ts.ParameterDeclaration; const isOptional = parameterDeclaration.questionToken != null || parameterDeclaration.initializer != null || parameterDeclaration.dotDotDotToken != null; ' TypeChecker方法。

  7. 要获取其默认表达式,您只需检查isOptionalParameter属性:

    initializer
  8. 要获取该类型,请使用propertyDeclaration.initializer; ' TypeChecker方法并传入节点的符号...这有点复杂,所以我赢了#39不要理解它(想想它与工会类型等有何不同)。

  9. 不要从头开始......

    我已经在TypeScript编译器api周围创建了一个包装器。只需将此代码与ts-simple-ast一起使用(编辑:以前这里谈到了我的旧ts-type-info库,但ts-simple-ast要好得多):

    getTypeOfSymbolAtLocation

    获得该方法后,从参数中获取所需的所有信息非常简单:

    import Project from "ts-simple-ast";
    
    // read more about setup here:
    // https://dsherret.github.io/ts-simple-ast/setup/adding-source-files
    const project = new Project({ tsConfigFilePath: "tsconfig.json" });
    const sourceFile = project.getSourceFileOrThrow("src/Foo.ts");
    const method = sourceFile.getClassOrThrow("Bar").getInstanceMethodOrThrow("foo");
    
相关问题