tree-sitter-typescript

0.23.2 · active · verified Fri Apr 10

tree-sitter-typescript provides pre-compiled TypeScript and TSX grammars for the `tree-sitter` parsing library in Python. It allows developers to parse TypeScript and TSX code into concrete syntax trees for advanced code analysis and manipulation. The library is actively and regularly updated, with the current stable version being 0.23.2.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install `tree-sitter-typescript` and `tree-sitter`, then load both the TypeScript and TSX grammars to parse respective code snippets. It shows how to initialize a parser, set the language, parse code, and access the resulting syntax tree's root node.

from tree_sitter import Language, Parser
import tree_sitter_typescript

# Load the TypeScript grammar
TS_LANGUAGE = Language(tree_sitter_typescript.language(), 'typescript')

# Create a parser and set its language
parser = Parser()
parser.set_language(TS_LANGUAGE)

# Code to parse
ts_code = b"""interface MyInterface { name: string; age?: number; }\nconst x: MyInterface = { name: 'Alice' };"""

# Parse the code
tree = parser.parse(ts_code)

# Access the root node
root_node = tree.root_node
print(f"Parsed TypeScript root node type: {root_node.type}")

# Load the TSX grammar
TSX_LANGUAGE = Language(tree_sitter_typescript.tsx_language(), 'tsx')
parser.set_language(TSX_LANGUAGE)

# TSX code to parse
tsx_code = b"""function App() { return <div>Hello, {name}</div>; }"""

# Parse the TSX code
tree_tsx = parser.parse(tsx_code)
root_node_tsx = tree_tsx.root_node
print(f"Parsed TSX root node type: {root_node_tsx.type}")

# Example of finding a node
interface_node = root_node.children[0] # Assuming interface declaration is the first child
print(f"First node in TS: {interface_node.type}, text: {interface_node.text.decode('utf8')}")

view raw JSON →