Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 211
samvv Avatar asked Jul 03 '17 14:07

samvv


People also ask

How do I assign two TypeScript types?

TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.

How TypeScript check types?

Using TypeScript type guards Checking a specific value's type at runtime is the primary function of type guards. This helps the TypeScript compiler, which then uses the information to become more predictive about the types. The above code snippet showcases the example of the type guard instanceof .

What is ?: In TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

What is type guard in TypeScript?

A type guard is a TypeScript technique used to get information about the type of a variable, usually within a conditional block. Type guards are regular functions that return a boolean, taking a type and telling TypeScript if it can be narrowed down to something more specific.


1 Answers

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

  • Expose isTypeAssignableTo in TypeChecker?
  • Proposal: Type Relationship API
  • Assignability checks in API

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.

like image 187
samvv Avatar answered Oct 13 '22 18:10

samvv