记录所有 JSX 属性但类型缩小的软件

Alt*_*ula 6 typescript

(1。目的

我正在尝试创建软件,该软件将JSX使用缩小的打字稿类型记录文件的所有属性。

输入文件:

test的属性div定义为{test:'hello'}因此仅接受hello单词作为string

const testAsConst = 'hello' as const;

const test = 'hello';

// both variables above works
<div test={test} />;
Run Code Online (Sandbox Code Playgroud)

预期输出:[ [ 'test', '"hello"' ] ]

(2)但是

没有as const输出的是[ [ 'test', 'string' ] ]

输出as const[ [ 'test', '"hello"' ] ]

这一but章的内容已经很明显了。我知道as const做了什么。但是这个例子可以工作吗,as const因为没有打字稿报告没有错误,所以它是hello而不是string没有as const......我希望你理解。

产生输出的软件源代码

import typescript from 'typescript';

const program = typescript.createProgram(['inputFile.tsx'], { target: typescript.ScriptTarget.ESNext });

const typeChecker = program.getTypeChecker();

for (const sourceFile of program.getSourceFiles()) {
  if (!sourceFile.isDeclarationFile) {
    const output = visit(sourceFile);

    console.log(output);
  }
}

function visit(node: typescript.Node, output2: [string, string][] = []): [string, string][] | undefined {
  if (typescript.isJsxAttribute(node)) {
    const attributeName = node.name.text;

    const symbol = typeChecker.getSymbolAtLocation(node.name);

    if (symbol) {
      const type = typeChecker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!);

      output2.push([attributeName, typeChecker.typeToString(type)]);
    }
  }

  typescript.forEachChild(node, node2 => {
    visit(node2, output2);
  });

  return output2;
}

Run Code Online (Sandbox Code Playgroud)