'How do I use the node-tree-sitter module from typescript?

From looking at pull requests & issues I see there are typescript definitions (possibly currently out of date) in the node-tree-sitter module; how do I access these definitions from typescript, and what would be the equivalent of the following node-tree-sitter sample javascript code in typescript?

const Parser = require('tree-sitter');
const JavaScript = require('tree-sitter-javascript');

const parser = new Parser();
parser.setLanguage(JavaScript);

const sourceCode = 'let x = 1; console.log(x);';
const tree = parser.parse(sourceCode);

console.log(tree.rootNode.toString());


Solution 1:[1]

The tree-sitter module doesn't have a separate @types/tree-sitter module (like some other modules) but instead bundles a tree-sitter.d.ts type definition file with the tree-sitter module itself. You can find this file in your node_modules/tree-sitter directory. TypeScript finds this file automatically when you import tree-sitter. Thus you can rewrite the sample JavaScript code in TypeScript as follows:

import Parser = require('tree-sitter');
import JavaScript = require('tree-sitter-javascript');

const parser: Parser = new Parser();
parser.setLanguage(JavaScript);

const sourceCode: string = 'let x = 1; console.log(x);';
const tree: Parser.Tree = parser.parse(sourceCode);

console.log(tree.rootNode.toString());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Boris Verkhovskiy