【发布时间】:2019-03-02 10:16:33
【问题描述】:
考虑如下界面:
interface X {
x: string
}
我正在尝试使用 typescript 编译器 API 来获取属性 x 的类型。到目前为止,这是我所拥有的:
import {
PropertySignature,
createSourceFile,
ScriptTarget,
ScriptKind,
SyntaxKind,
InterfaceDeclaration,
Identifier,
} from 'typescript'
describe('Compiler test', () => {
it('should be able to find type information about X.x', () => {
const sourceText = 'interface X { x: string }'
const ast = createSourceFile('source.ts', sourceText, ScriptTarget.ES5, false, ScriptKind.TS)
const interfaceX = ast
.getChildAt(0)
.getChildren()
.find((child) => child.kind === SyntaxKind.InterfaceDeclaration) as InterfaceDeclaration
const propX = interfaceX.members.find((member) => (member.name as Identifier).escapedText === 'x')
console.log(JSON.stringify(propX, null, 2))
})
})
现在propX节点的内容如下:
{
"pos": 13,
"end": 23,
"flags": 0,
"kind": 151,
"name": {
"pos": 13,
"end": 15,
"flags": 0,
"escapedText": "x"
},
"type": {
"pos": 16,
"end": 23,
"flags": 0,
"kind": 137
}
}
从中可以清楚地提取节点的名称,但是类型节点似乎没有任何有用的信息。
我如何获得房产的类型信息?我只需要"string"。
【问题讨论】:
-
我肯定会推荐为此使用类型检查器 API 而不是遍历 AST。看起来你会创建一个
Program,调用getTypeChecker,获取接口的符号(我不知道如何做那部分),然后使用getDeclaredTypeOfSymbol和getPropertyOfType。我没有写答案,因为我没有完整的答案。 -
谢谢马特,这是一个好的开始!
标签: typescript abstract-syntax-tree typescript-compiler-api