Let's dive into the TypeScript compiler API to extract type information from a given interface:
interface X {
x: string
}
In this example, we are specifically interested in getting the type of property x
. Here's a snippet of code showcasing how we can achieve this using the TypeScript compiler API:
import {
PropertySignature,
createSourceFile,
ScriptTarget,
ScriptKind,
SyntaxKind,
InterfaceDeclaration,
Identifier,
} from 'typescript'
describe('Compiler exploration', () => {
it('should retrieve the type of X.x property', () => {
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))
})
})
The retrieved node for propX
reveals the structure and properties related to the desired property:
{
"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
}
}
While the name of the node is readily accessible, extracting the actual type information might prove to be more challenging due to insufficient data within the type node.
How can we obtain the type information for the property? Our goal is to acquire the type "string"
associated with property x
.