Search code examples
typescriptcompiler-constructiontypescript-compiler-api

Using the TypeScript type checker to see if two types are assignable


I'm building a small script that scans for all interfaces that have a member of a given type using the TypeScript Compiler API, of which the source can be found here. I inspect the members of these classes to see how they are interlinked.

My question is: how do I know when a type is assignable to another type? I searched the TypeChecker for a method but I couldn't find one. Does anyone by any chance have any pointers? Here's an example of something that should be able to get analysed:

export enum ASTKind {
  Number,
  Addition,
  Multiplication,
}

export interface AST {
  kind: ASTKind  
}

export interface BinaryExpression extends AST {
  left: AST
  right: AST
}

export interface Addition extends BinaryExpression {
  kind: ASTKind.Addition 
}

export interface Multiplication extends BinaryExpression {
  kind: ASTKind.Multiplication 
}

Essentially, I want a predicate that says whether ASTKind.Multiplication is assignable to ASTKind (which is true in this case).


Solution

  • I've found it: seems like it is currently not possible:

    I created my own fork which exposes this function. I will try to maintain it so if anyone is interested he or she can just use the fork until upstream follows.