我正在尝试创建软件,该软件将
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"' ] ]
没有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)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |