当我需要生成一些C#代码时,比如从xsd模式生成DTO类,或者生成excel表,我使用了一些roslyn API.

Typescript 有相似之处吗?

[编辑]:我最终使用了ts-morph

推荐答案

从2018年10月起,您可以使用标准的TypeScript API来实现这一点

import ts = require("typescript");

function makeFactorialFunction() {
  const functionName = ts.createIdentifier("factorial");
  const paramName = ts.createIdentifier("n");
  const parameter = ts.createParameter(
    /*decorators*/ undefined,
    /*modifiers*/ undefined,
    /*dotDotDotToken*/ undefined,
    paramName
  );

  const condition = ts.createBinary(
    paramName,
    ts.SyntaxKind.LessThanEqualsToken,
    ts.createLiteral(1)
  );

  const ifBody = ts.createBlock(
    [ts.createReturn(ts.createLiteral(1))],
    /*multiline*/ true
  );
  const decrementedArg = ts.createBinary(
    paramName,
    ts.SyntaxKind.MinusToken,
    ts.createLiteral(1)
  );
  const recurse = ts.createBinary(
    paramName,
    ts.SyntaxKind.AsteriskToken,
    ts.createCall(functionName, /*typeArgs*/ undefined, [decrementedArg])
  );
  const statements = [ts.createIf(condition, ifBody), ts.createReturn(recurse)];

  return ts.createFunctionDeclaration(
    /*decorators*/ undefined,
    /*modifiers*/ [ts.createToken(ts.SyntaxKind.ExportKeyword)],
    /*asteriskToken*/ undefined,
    functionName,
    /*typeParameters*/ undefined,
    [parameter],
    /*returnType*/ ts.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
    ts.createBlock(statements, /*multiline*/ true)
  );
}

const resultFile = ts.createSourceFile(
  "someFileName.ts",
  "",
  ts.ScriptTarget.Latest,
  /*setParentNodes*/ false,
  ts.ScriptKind.TS
);
const printer = ts.createPrinter({
  newLine: ts.NewLineKind.LineFeed
});
const result = printer.printNode(
  ts.EmitHint.Unspecified,
  makeFactorialFunction(),
  resultFile
);

console.log(result);

摄于此:

Typescript相关问答推荐

具有实体的ngrx SignalStore中的动态类型

类型脚本:类型是通用的,只能索引以供阅读.(2862)"

为什么在TypScript中写入typeof someArray[number]有效?

TypScript手册中的never[]参数类型是什么意思?

如果存在ts—mock—imports,我们是否需要typescpt中的IoC容器

如何使用泛型类型访问对象

扩展函数签名中的参数类型,而不使用泛型

使某些(嵌套)属性成为可选属性

如何解决类型T不能用于索引类型{ A:typeof A; B:typeof B;. }'

获取一个TypeScrip对象,并将每个属性转换为独立对象的联合

部分更新类型的类型相等

ANGLE订阅要么不更新价值,要么不识别价值变化

如何将spread operator与typescripts实用程序类型`参数`一起使用

带投掷的收窄类型

在Google授权后由客户端接收令牌

基于泛型的类型脚本修改类型

递归类型别名的Typescript 使用

仅当定义了值时才按值筛选数组

如何在TypeScript中将元组与泛型一起使用?

Typescript泛型验证指定了keyof的所有键