From 968a685f278991c64bc59e61ca49ac345d4a2b48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josh=20Goldberg=20=E2=9C=A8?= Date: Fri, 6 Oct 2023 01:36:32 +0200 Subject: [PATCH] Added 'Type Checker APIs' section prefix to type checker docs (#320) * Added 'Type Checker APIs' section prefix to type checker docs * Apply suggestions from code review Co-authored-by: Daniel Rosenwasser --------- Co-authored-by: Daniel Rosenwasser --- Using-the-Compiler-API.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Using-the-Compiler-API.md b/Using-the-Compiler-API.md index 3c8fd775..9c5352bb 100644 --- a/Using-the-Compiler-API.md +++ b/Using-the-Compiler-API.md @@ -607,6 +607,42 @@ const result = printer.printNode(ts.EmitHint.Unspecified, makeFactorialFunction( console.log(result); ``` +## Type Checker APIs + +Programs contain a `TypeChecker` object that provides methods for retrieving and reasoning about the types of syntax tree nodes. +Type checker APIs generally work with two types of representations alongside AST nodes: + +* `Symbol`s: describes how the type system views a declared entity, such as a class, function, or variable. +* `Type`s: describes the backing type that entities may be declared as. + These often have a backing `Symbol` pointing to their declaration(s). + +For example, given a single function declaration like: + +```ts +function greet() { + console.log("Hello, world!"); +} +``` + +TypeScript will create a `Symbol` in the containing scope for `greet`. +When looking up ("resolving") an identifier with the name `greet`, that `Symbol` can be retrieved. +This `Symbol` will contain information about how `greet` was declared, and can be used to gain information about the type of `greet`. + +On that note, TypeScript will also create a type describing `greet`, which is effectively the type `() => void` - a function with no parameters and a `void` return type. +In this case, the type will be backed by the original symbol associated with `greet`. + +The type checker can be retrieved like `program.getTypeChecker()`. +Commonly used type checker APIs include: + +* `getSymbolAtLocation(node)`: retrieves the `Symbol` associated with an AST node +* `getTypeAtLocation(node)`: retrieves the `Type` associated with an AST node +* `getTypeOfSymbolAtLocation(symbol, node)`: retrieves the `Type` associated with a symbol at a specific AST node +* `typeToString(type)`: prints a type to a human-readable string + +> The type checker concept of `Symbol` only coincidentally has the same name as the JavaScript concept of `Symbol`. +> JavaScript's `Symbol` is a runtime primitive that is used to create unique identifiers. +> TypeScript's `Symbol` is unrelated to the JavaScript `Symbol` and is used to represent the type system's view of an entity. + ### Using the Type Checker In this example we will walk the AST and use the checker to serialize class information.