Рассмотрим следующий интерфейс:
interface X {
x: string
}
Я пытаюсь использовать 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"
.