使用TypeScript类型检查器查看两种类型是否可分配 [英] Using the TypeScript type checker to see if two types are assignable
问题描述
我正在构建一个小的脚本,该脚本使用 TypeScript编译器API ,其源可以在此处。我检查了这些类的成员,以了解它们是如何相互链接的。
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.
我的问题是:如何知道一个类型何时可以分配给另一个类型?我在 TypeChecker
中搜索了一种方法,但找不到。有没有人有任何指针?以下是应该能够进行分析的示例:
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
}
本质上,我想要一个谓词,说明 ASTKind.Multiplication
是否可分配给 ASTKind
(在这种情况下是正确的。)。
Essentially, I want a predicate that says whether ASTKind.Multiplication
is assignable to ASTKind
(which is true in this case).
推荐答案
我找到了它:好像是当前不可能:
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.
这篇关于使用TypeScript类型检查器查看两种类型是否可分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!