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).
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.
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 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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With