Typescript: Expose `getImmediateAliasedSymbol()` in Type Checker API

Created on 12 Mar 2020  路  2Comments  路  Source: microsoft/TypeScript

Search Terms

compiler api, type checker, alised symbol, symbol links

Suggestion

Expose getImmediateAliasedSymbol() in Type Checker API.

Given this source:

import { A } from "./a";

type B = A;
type C = B;
type D = C;

export { D };

it would be helpful to have a public API that could follow symbol aliases (one by one) from D to A's original declaration. Simplest way of achieving this that I could find is to use typeChecker.getImmediateAliasedSymbol() API. This will give D's symbol for the export specifier, C's symbol for D and so on... However typescript.d.ts does not have the type for it.

Use Cases

What do you want to use this for?

I am working on a tool that crawls .d.ts files and removes type declarations that are not part of the public API. It starts crawling the graph from exports and does liveness check by exploring AST nodes, symbols and types.

What shortcomings exist with current approaches?

typeChecker.getAliasedSymbol() is close to what I'm looking for but it follows all the symbol links and skips intermediate nodes.

type A = number;
type B = A;
type C = B;

export { C };

In this case, I would like consider A, B and C as live. Using typeChecker.getAliasedSymbol() I can only detect A is live because getAliasedSymbol(symbolC) will give back A's symbol.

Examples

const checker = program.getTypeChecker();

if (symbol.flags === ts.SymbolFlags.Alias) {
    // this code works at runtime currently
    // but requires a cast in order to acces at `getImmediateAliasedSymbol`
    const nextLink = (checker as any).getImmediateAliasedSymbol(symbol);
    if (nextLink) {
        // consider it live
    }
}

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
In Discussion Suggestion

Most helpful comment

Yes, I'm fine with this.

All 2 comments

@ahejlsberg would you be comfortable with this?

Yes, I'm fine with this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nitzantomer picture nitzantomer  路  135Comments

rbuckton picture rbuckton  路  139Comments

RyanCavanaugh picture RyanCavanaugh  路  205Comments

sandersn picture sandersn  路  265Comments

jonathandturner picture jonathandturner  路  147Comments