Skip to content

Commit

Permalink
Added 'Type Checker APIs' section prefix to type checker docs (#320)
Browse files Browse the repository at this point in the history
* Added 'Type Checker APIs' section prefix to type checker docs

* Apply suggestions from code review

Co-authored-by: Daniel Rosenwasser <[email protected]>

---------

Co-authored-by: Daniel Rosenwasser <[email protected]>
  • Loading branch information
JoshuaKGoldberg and DanielRosenwasser committed Oct 5, 2023
1 parent 4426b5c commit 968a685
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Using-the-Compiler-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 968a685

Please sign in to comment.