问题
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).
回答1:
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.
回答2:
Typescript is just a superset of JavaScript. You cannot make 'on the run' verifications with TypeScript that you are not able to do with Javascript.
JavaScript does not have "classes" or "inherit" information. It only know creating objects and verify if an instance is instance of an object.
JavaScript does have a method called 'instaceof' that verifies if a instance is instance of a class. for instance.
var x = new ASTKind.Multiplication
x instanceof ASTKind.Multiplication // will return true
x instanceof AST // sill also return true
来源:https://stackoverflow.com/questions/44888163/using-the-typescript-type-checker-to-see-if-two-types-are-assignable