>e.f;
```
```tree-sitter grammar
(program
(expression_statement (type_assertion
(type_arguments (type_identifier))
(identifier)))
(expression_statement (type_assertion
(type_arguments (generic_type
(type_identifier)
(type_arguments (type_identifier))))
(member_expression
(identifier)
(property_identifier)))))
```
--------------------------------
### Object Literals with Boolean and Number Values
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt
Demonstrates parsing of object literals containing key-value pairs where values are either booleans (true) or numbers. This is a fundamental structure for representing data objects in TypeScript.
```tree-sitter grammar
(program
(expression_statement
(object
(pair
key: (property_identifier)
value: (true))
(pair
key: (property_identifier)
value: (true))
(pair
key: (property_identifier)
value: (true))))
(expression_statement
(object
(pair
key: (property_identifier)
value: (number))
(pair
key: (property_identifier)
value: (number))
(pair
key: (property_identifier)
value: (number)))))
```
--------------------------------
### TypeScript 'typeof' Expressions Grammar
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt
This snippet illustrates the tree-sitter grammar for 'typeof' expressions in TypeScript, used to determine the type of a variable or expression. It covers comparisons with string literals.
```tree-sitter grammar
(program
(expression_statement
(binary_expression
(unary_expression
(class
(class_body)))
(string
(string_fragment))))
(expression_statement
(binary_expression
(binary_expression
(unary_expression
(identifier))
(string
(string_fragment)))
(binary_expression
(unary_expression
(member_expression
(identifier)
(property_identifier)))
(string
(string_fragment))))))
```
--------------------------------
### TypeScript Index Type Queries
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/declarations.txt
Demonstrates the Tree-sitter grammar for 'keyof' operator in TypeScript, used to create a union type of the property names of an object type. This example extracts keys from a Pick utility type.
```typescript
export type Extracted = keyof Pick
```
--------------------------------
### Exported Default Function Signature
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt
Shows an exported default function signature in TypeScript. This defines the function's name, parameters, and return type without providing an implementation body. It's useful for declarations and interfaces.
```typescript
export default function foo(): bar
```
--------------------------------
### TypeScript Mapped Types with 'as' Clause
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Illustrates TypeScript mapped types where the 'as' clause is used to transform or create new keys. This includes examples with template literal types for key renaming and unions for multiple key patterns.
```typescript
type A = { [B in keyof C & string as `get${Capitalize}`]: () => A[B] };
type A = { [B in keyof C & string as `${P}1` | `${P}2`]: A[B] }
```
--------------------------------
### Parse TypeScript Function Signature with Tree-sitter
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt
This grammar rule defines how to parse a TypeScript function signature. It captures the function identifier, its formal parameters, and the return type annotation. This is useful for static analysis tools that need to understand function definitions.
```tree-sitter grammar
(function_signature
(identifier)
(formal_parameters)
(type_annotation (predefined_type))))
```
--------------------------------
### TypeScript Assertion Function Types
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Defines the syntax for TypeScript assertion functions, which are used to narrow down the type of a variable. It includes examples for general assertions and type-specific assertions (type predicates).
```typescript
declare const f: (x: any) => asserts x;
declare const g: (x: any) => asserts x is number;
```
--------------------------------
### TypeScript Objects with Reserved Word Keys Grammar
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt
This snippet illustrates the tree-sitter grammar for parsing TypeScript objects where reserved words are used as keys. This is valid in TypeScript when using computed property names or specific object literal syntaxes.
```tree-sitter grammar
{
public: true,
private: true,
readonly: true
};
```
--------------------------------
### TypeScript Conditional Types
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Provides examples of TypeScript conditional types, which allow for defining types based on a condition. This includes basic conditional types, overloaded function types used in conditionals, and inferring types within conditionals.
```typescript
type T = X extends Y ? Z : Y
type T = X extends ?Y ? ?X : Y
type F = ((t: T) => X extends Y ? X : Y) extends ((t: T) => X extends Y ? Y : X) ? X : Y
type F = (t: T) => X extends Y ? X : Y extends (t: T) => X extends Y ? Y : X ? X : Y
type T = T extends X ? Y : X
type T = X extends (infer X)[] ? X : never;
type T = T extends { x: infer X } ? X : never;
type T = T extends { x: infer X extends number } ? X : never;
```
--------------------------------
### TypeScript Assertion Functions (Value Check)
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Shows the syntax for assertion functions in TypeScript that check a value. The example `function f(x: any): asserts x {}` demonstrates how the `asserts` keyword is used to indicate a type predicate that narrows down the type of a variable.
```typescript
function f(x: any): asserts x {
}
```
```tree-sitter-grammar
(program
(function_declaration
(identifier)
(formal_parameters
(required_parameter
(identifier)
(type_annotation
(predefined_type))))
(asserts_annotation
(asserts
(identifier)))
(statement_block)))
```
--------------------------------
### CMake Project Configuration
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/CMakeLists.txt
Sets up the minimum CMake version, project name, version, description, and homepage URL. It also specifies the programming languages used (C) and configures options for shared libraries and allocator reuse.
```cmake
cmake_minimum_required(VERSION 3.13)
project(tree-sitter-typescript
VERSION "0.23.2"
DESCRIPTION "TypeScript and TSX grammars for tree-sitter"
HOMEPAGE_URL "https://github.com/tree-sitter/tree-sitter-typescript"
LANGUAGES C)
option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
option(TREE_SITTER_REUSE_ALLOCATOR "Reuse the library allocator" OFF)
set(TREE_SITTER_ABI_VERSION 14 CACHE STRING "Tree-sitter ABI version")
if(NOT ${TREE_SITTER_ABI_VERSION} MATCHES "^[0-9]+$")
unset(TREE_SITTER_ABI_VERSION CACHE)
message(FATAL_ERROR "TREE_SITTER_ABI_VERSION must be an integer")
endif()
find_program(TREE_SITTER_CLI tree-sitter DOC "Tree-sitter CLI")
include(GNUInstallDirs)
```
--------------------------------
### Parse TypeScript and TSX with Go tree-sitter
Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt
This Go code snippet demonstrates how to use the `go-tree-sitter` library with the `tree-sitter-typescript` grammar. It shows the initialization of the parser for both TypeScript and TSX, parsing sample code, and basic tree traversal. Dependencies include `go-tree-sitter` and `tree-sitter-typescript`. It takes byte slices of code as input and outputs the root node type, child count, and error status.
```go
package main
import (
"context"
"fmt"
sitter "github.com/tree-sitter/go-tree-sitter"
tree_sitter_typescript "github.com/tree-sitter/tree-sitter-typescript"
)
func main() {
// Parse TypeScript code
typescript := sitter.NewLanguage(tree_sitter_typescript.LanguageTypescript())
parser := sitter.NewParser()
parser.SetLanguage(typescript)
sourceCode := []byte(`
enum Direction {
North,
South,
East,
West
}
interface Point {
x: number;
y: number;
}
function move(point: Point, direction: Direction, distance: number): Point {
switch (direction) {
case Direction.North:
return { ...point, y: point.y + distance };
case Direction.South:
return { ...point, y: point.y - distance };
case Direction.East:
return { ...point, x: point.x + distance };
case Direction.West:
return { ...point, x: point.x - distance };
}
}
`)
tree := parser.Parse(sourceCode, nil)
defer tree.Close()
rootNode := tree.RootNode()
fmt.Printf("Root node type: %s\n", rootNode.Type())
fmt.Printf("Number of children: %d\n", rootNode.ChildCount())
fmt.Printf("Has errors: %v\n", rootNode.HasError())
// Walk the tree
cursor := sitter.NewTreeCursor(rootNode)
defer cursor.Close()
visitNode(cursor, 0)
// Parse TSX code
tsx := sitter.NewLanguage(tree_sitter_typescript.LanguageTSX())
parser.SetLanguage(tsx)
tsxCode := []byte(`
interface HeaderProps {
title: string;
subtitle?: string;
}
const Header: React.FC = ({ title, subtitle }) => {
return (
{title}
{subtitle && {subtitle}
}
);
};
`)
tsxTree := parser.Parse(tsxCode, nil)
defer tsxTree.Close()
fmt.Printf("\nTSX Root node type: %s\n", tsxTree.RootNode().Type())
fmt.Printf("TSX Has errors: %v\n", tsxTree.RootNode().HasError())
}
func visitNode(cursor *sitter.TreeCursor, depth int) {
node := cursor.CurrentNode()
indent := ""
for i := 0; i < depth; i++ {
indent += " "
}
fmt.Printf("%s%s\n", indent, node.Type())
if cursor.GoToFirstChild() {
visitNode(cursor, depth+1)
cursor.GoToParent()
}
for cursor.GoToNextSibling() {
visitNode(cursor, depth)
}
}
```
--------------------------------
### TypeScript String Manipulation with Template Literals
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Provides examples of advanced string manipulation using TypeScript's template literal types. This includes inferring parts of a string, applying conditional logic based on string content, and constructing new string types dynamically. These examples often involve recursive type definitions or complex conditional checks.
```typescript
type StringToNumber = S extends `${infer N extends number}` ? N : never;
type Trim = S extends `${infer R}` ? Trim : S;
type PrefixSuffix = S extends `${infer Prefix}${infer Suffix}` ? `${P}${Prefix}${Suffix}${Suf}` : never;
```
--------------------------------
### Parse TypeScript and TSX with tree-sitter in Rust
Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt
Demonstrates parsing both TypeScript and TSX code using the tree-sitter-typescript Rust crate. It shows how to initialize the parser, load language definitions (LANGUAGE_TYPESCRIPT, LANGUAGE_TSX), parse source code, and utilize syntax highlighting queries. Dependencies include the `tree-sitter` and `tree-sitter-typescript` crates.
```rust
use tree_sitter::{Parser, Query, QueryCursor};
use tree_sitter_typescript::{LANGUAGE_TYPESCRIPT, LANGUAGE_TSX, HIGHLIGHTS_QUERY, TYPESCRIPT_NODE_TYPES};
fn main() {
// Parse TypeScript code
let mut parser = Parser::new();
let language = LANGUAGE_TYPESCRIPT.into();
parser.set_language(&language)
.expect("Error loading TypeScript parser");
let source_code = r#"
function fibonacci(n: number): number {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
type Result = { ok: true; value: T } | { ok: false; error: E };
async function fetchData(url: string): Promise> {
try {
const response = await fetch(url);
const data = await response.json();
return { ok: true, value: data };
} catch (error) {
return { ok: false, error: error as Error };
}
}
"#;
let tree = parser.parse(source_code, None).unwrap();
let root_node = tree.root_node();
assert!(!root_node.has_error());
println!("Parsed successfully: {}", root_node.kind());
println!("Byte range: {}..{}", root_node.start_byte(), root_node.end_byte());
// Use syntax highlighting query
let query = Query::new(&language, HIGHLIGHTS_QUERY)
.expect("Error creating query");
let mut cursor = QueryCursor::new();
let captures = cursor.captures(&query, root_node, source_code.as_bytes());
for (match_, _) in captures {
for capture in match_.captures {
let name = &query.capture_names()[capture.index as usize];
let text = &source_code[capture.node.byte_range()];
println!( "{}: {}", name, text);
}
}
// Parse TSX code
parser.set_language(&LANGUAGE_TSX.into())
.expect("Error loading TSX parser");
let tsx_code = r#"
const TodoList: React.FC<{ items: string[] }> = ({ items }) => (
{items.map((item, index) => (
- {item}
))}
);
"#;
let tsx_tree = parser.parse(tsx_code, None).unwrap();
assert!(!tsx_tree.root_node().has_error());
println!("TSX parsed successfully");
}
```
--------------------------------
### Use Tree-sitter Queries for Syntax Highlighting in Node.js
Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt
Shows how to use Tree-sitter's query system in Node.js to extract syntax information for tasks like highlighting. It loads a TypeScript language configuration, reads a query file (e.g., highlights.scm), parses code, and then iterates through the query captures to identify code elements and their locations.
```javascript
// Node.js - Using queries for syntax highlighting
const Parser = require('tree-sitter');
const { typescript } = require('tree-sitter-typescript');
const fs = require('fs');
const parser = new Parser();
parser.setLanguage(typescript);
// The query files are in the queries/ directory
const highlightsQuery = fs.readFileSync('./queries/highlights.scm', 'utf8');
const query = typescript.language.query(highlightsQuery);
const code = `
function calculate(x: number, y: number): number {
const result = x + y;
return result;
}
`;
const tree = parser.parse(code);
const captures = query.captures(tree.rootNode);
captures.forEach(capture => {
const { name, node } = capture;
const text = code.slice(node.startIndex, node.endIndex);
console.log(`${name}: "${text}" at ${node.startPosition.row}:${node.startPosition.column}`);
});
// Example output:
// function: "function" at 1:0
// function.name: "calculate" at 1:9
// variable.parameter: "x" at 1:19
// type: "number" at 1:22
// variable.parameter: "y" at 1:30
// type: "number" at 1:33
// keyword: "const" at 2:2
// variable: "result" at 2:8
// keyword: "return" at 3:2
```
--------------------------------
### Parse TypeScript and TSX in Swift using Tree-sitter
Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt
Demonstrates how to use the TreeSitterTypeScript and TreeSitterTSX targets within the SwiftTreeSitter framework to parse TypeScript and TSX code. It initializes a parser, sets the appropriate language, parses source code, and asserts properties of the resulting syntax tree.
```swift
import XCTest
import SwiftTreeSitter
import TreeSitterTypeScript
import TreeSitterTSX
class TypeScriptParsingTests: XCTestCase {
func testParseTypeScript() throws {
let parser = Parser()
let language = Language(language: tree_sitter_typescript())
try parser.setLanguage(language)
let sourceCode = """
interface Product {
id: string;
name: string;
price: number;
inStock: boolean;
}
class ShoppingCart {
private items: Map = new Map();
addItem(product: Product, quantity: number = 1): void {
const currentQty = this.items.get(product.id) ?? 0;
this.items.set(product.id, currentQty + quantity);
}
getTotalItems(): number {
return Array.from(this.items.values())
.reduce((sum, qty) => sum + qty, 0);
}
}
const cart = new ShoppingCart();
"""
let tree = parser.parse(sourceCode)
XCTAssertNotNil(tree)
let rootNode = tree!.rootNode
XCTAssertEqual(rootNode.nodeType, "program")
XCTAssertFalse(rootNode.hasError)
XCTAssertTrue(rootNode.childCount > 0)
print("Parsed TypeScript successfully")
print("Root node: \(rootNode.nodeType)")
print("Children count: \(rootNode.childCount)")
}
func testParseTSX() throws {
let parser = Parser()
let language = Language(language: tree_sitter_tsx())
try parser.setLanguage(language)
let tsxCode = """
import { useState, useEffect } from 'react';
interface UserCardProps {
userId: number;
onUserLoad?: (user: User) => void;
}
const UserCard: React.FC = ({ userId, onUserLoad }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
onUserLoad?.(data);
});
}, [userId]);
if (loading) {
return Loading...
;
}
return (
{user?.name}
{user?.email}
);
};
export default UserCard;
"""
let tree = parser.parse(tsxCode)
XCTAssertNotNil(tree)
let rootNode = tree!.rootNode
XCTAssertEqual(rootNode.nodeType, "program")
XCTAssertFalse(rootNode.hasError)
print("Parsed TSX successfully")
}
}
```
--------------------------------
### Flow Type Parameter Constraint Syntax
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Demonstrates Flow's syntax for constraining type parameters in generic types. This example constrains a type parameter T to extend Element.
```flow
type HandlerFunction = void
```
```tree-sitter-typescript
(program
(type_alias_declaration
(type_identifier)
(type_parameters
(type_parameter
(type_identifier)
(constraint
(type_identifier))))
(predefined_type)))
```
--------------------------------
### TypeScript Constructor Type Declaration
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Demonstrates the syntax for a constructor type in TypeScript, including generic type parameters and multiple parameters. The grammar snippet shows the tree-sitter nodes for type parameters, formal parameters, and the return type identifier.
```typescript
let x: new < T1, T2 > ( p1, p2 ) => R;
```
```tree-sitter-grammar
(program
(lexical_declaration
(variable_declarator
(identifier)
(type_annotation
(constructor_type
(type_parameters
(type_parameter
(type_identifier))
(type_parameter
(type_identifier)))
(formal_parameters
(required_parameter
(identifier))
(required_parameter
(identifier)))
(type_identifier))))))
```
--------------------------------
### Subdirectory Inclusion and Testing
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/CMakeLists.txt
Includes the 'typescript' and 'tsx' subdirectories, which likely contain their respective grammar definitions and build configurations. Also defines a custom target 'ts-test' to run tests using the tree-sitter CLI.
```cmake
add_subdirectory(typescript tree-sitter-typescript)
add_subdirectory(tsx tree-sitter-tsx)
add_custom_target(ts-test "${TREE_SITTER_CLI}" test
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "tree-sitter test")
```
--------------------------------
### Require TypeScript and TSX Grammars for Tree-sitter
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/README.md
Demonstrates how to import and access the TypeScript and TSX grammars provided by the 'tree-sitter-typescript' library. These grammars are essential for parsing TypeScript and TSX code with the tree-sitter parsing library.
```javascript
require("tree-sitter-typescript").typescript; // TypeScript grammar
require("tree-sitter-typescript").tsx; // TSX grammar
```
--------------------------------
### TypeScript Class Methods with Keyword Names
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/declarations.txt
Demonstrates how Tree-sitter handles method declarations in TypeScript classes where method names might be keywords. This includes methods with accessibility modifiers and type annotations.
```typescript
class Foo {
private async() {};
get(): Result {};
private set(plugin) {};
}
```
```tree-sitter-typescript
(program
(class_declaration
(type_identifier)
(class_body
(method_definition
(accessibility_modifier)
(property_identifier)
(formal_parameters)
(statement_block))
(method_definition
(property_identifier)
(formal_parameters)
(type_annotation
(type_identifier))
(statement_block))
(method_definition
(accessibility_modifier)
(property_identifier)
(formal_parameters
(required_parameter
(identifier)))
(statement_block)))))
```
--------------------------------
### TypeScript Function Type Syntax
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt
Illustrates the TypeScript syntax for defining function types, including parameter names and their respective types, along with the return type.
```typescript
let score: (string: string, query: string) => number
```
```tree-sitter-typescript
(program
(lexical_declaration
(variable_declarator
(identifier)
(type_annotation
(function_type
(formal_parameters
(required_parameter
(identifier)
(type_annotation
(predefined_type)))
(required_parameter
(identifier)
(type_annotation
(predefined_type))))
(predefined_type))))))
```
--------------------------------
### TypeScript Array with Empty Elements Grammar
Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt
This snippet shows the tree-sitter grammar for parsing arrays in TypeScript that contain empty elements. It represents an array with interspersed identifiers and empty slots.
```tree-sitter grammar
(program
(expression_statement
(array
(identifier)
(identifier)
(identifier))))
```