如何以编程方式提取 VS Code 工具提示打字稿信息?

问题描述 投票:0回答:1

比如我有这个功能:

import * as EC2 from "@aws-sdk/client-ec2";

const ec2 = new EC2.EC2({ region: "us-west-2" });

export async function getInfra() {
  const describeVpcs = await ec2.describeVpcs();

  const describeSubnets = await ec2.describeSubnets({
    Filters: [
      {
        Name: "vpc-id",
        Values: describeVpcs.Vpcs?.map((vpc) => vpc.VpcId!),
      },
    ],
  });

  const subnetIds = describeSubnets.Subnets?.map((subnet) => subnet.SubnetId!);

  return { describeVpcs, describeSubnets, subnetIds };
}

VS Code 提供了很棒的工具提示悬停:

function getInfra(): Promise<{
    describeVpcs: EC2.DescribeVpcsCommandOutput;
    describeSubnets: EC2.DescribeSubnetsCommandOutput;
    subnetIds: string[] | undefined;
}>

我只是希望能够使用脚本以编程方式生成它。我该怎么做?

typescript visual-studio-code static-analysis
1个回答
0
投票

哇,ts 多么优雅啊!

const program = ts.createProgram([entryFile], {
    target: ts.ScriptTarget.Latest,
    module: ts.ModuleKind.CommonJS,
    noResolve: false,
    skipLibCheck: true,
  });

const checker = program.getTypeChecker();
const sourceFile = program.getSourceFile(entryFile);

(function importsAndExportsFrom(sourceFile: ts.SourceFile) {
  ts.forEachChild(sourceFile, (node) => {
    switch (node.kind) {
      case ts.SyntaxKind.ExportDeclaration:
      case ts.SyntaxKind.ImportDeclaration: {
        const decl = node as ts.ImportDeclaration | ts.ExportDeclaration;
        const module = decl.moduleSpecifier;
        const symbol = checker.getSymbolAtLocation(module);
        if (!module || !symbol || module.getText().includes(pkg.name)) {
          return;
        }
        importsAndExportsFrom(symbol.declarations.pop() as ts.SourceFile);
        break;
      }
      case ts.SyntaxKind.FunctionDeclaration: {
        const func = node as ts.FunctionDeclaration;
        const name = func.name.getText();
        const signature = checker.getSignatureFromDeclaration(func);
        const parameters = func.parameters.map((p) => ({
          name: p.name.getText(),
          type: p.type.getText(),
        }));
        const returnType = checker.typeToString(
          checker.getReturnTypeOfSignature(signature),
          undefined,
          ts.TypeFormatFlags.NoTruncation
        );
        break;
      }
      default:
        break;
    }
  });
})(sourceFile);
© www.soinside.com 2019 - 2024. All rights reserved.