如何通过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用于创建类型断言表达式,它接收两个参数:- 第一个参数是需要添加断言的目标表达式(即原来的数组字面量)
- 第二个参数是断言的类型节点,这里通过
createKeywordTypeNode(ts.SyntaxKind.ConstKeyword)生成const关键字对应的类型节点
执行这段代码后,生成的结果就是你需要的:
const myArray = ["entry1", "entry2"] as const
内容的提问来源于stack exchange,提问作者Niro
相关产品推荐
相关产品推荐

