You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过TypeScript Compiler API为数组添加as const断言

解决方案

要给生成的数组添加as const类型断言,你需要用ts.factory.createAsExpression把数组字面量表达式包裹起来,作为变量声明的初始化值。

修改后的代码如下:

const myArray = ts.factory.createVariableDeclarationList(
    [
      ts.factory.createVariableDeclaration(
        'myArray',
        undefined,
        undefined,
        // 用createAsExpression包裹数组字面量,添加as const断言
        ts.factory.createAsExpression(
          ts.factory.createArrayLiteralExpression([
            ts.factory.createStringLiteral('entry1'), 
            ts.factory.createStringLiteral('entry2')
          ]),
          ts.factory.createKeywordTypeNode(ts.SyntaxKind.ConstKeyword)
        )
      )
    ],
    ts.NodeFlags.Const
  )

关键改动说明

  • createAsExpression用于创建类型断言表达式,它接收两个参数:
    1. 第一个参数是需要添加断言的目标表达式(即原来的数组字面量)
    2. 第二个参数是断言的类型节点,这里通过createKeywordTypeNode(ts.SyntaxKind.ConstKeyword)生成const关键字对应的类型节点

执行这段代码后,生成的结果就是你需要的:

const myArray = ["entry1", "entry2"] as const

内容的提问来源于stack exchange,提问作者Niro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:01:16