简体   繁体   English

如何使用 TypeScript Compiler API 提取数组的类型

[英]How can I use the TypeScript Compiler API to extract the type of an array

How can I use the TypeScript Compiler API to extract the type of an array?如何使用 TypeScript Compiler API 提取数组的类型? For example given this source:例如给出这个来源:

let a: string[] = []

How can I go from getting the type string[] to just string ?我怎样才能从获取类型string[]到只是string

ts-morph makes this easy but I haven't figured out how to replicate it with the raw TS Compiler API. ts-morph使这变得简单,但我还没有想出如何使用原始 TS 编译器 API 复制它。

It seems that I need to use checker.getTypeArguments() but it wants a ts.TypeReference type which I don't know how to create.似乎我需要使用checker.getTypeArguments()但它想要一个我不知道如何创建的ts.TypeReference类型。

An array type such as string[] will be in the form:诸如string[]类的数组类型将采用以下形式:

Array<string>

If you have one of these types, you can just assert it as a ts.TypeReference and pass it into TypeChecker#getTypeArguments :如果您有这些类型之一,则可以将其断言为ts.TypeReference并将其传递给TypeChecker#getTypeArguments

const typeArgs = typeChecker.getTypeArguments(arrayType as ts.TypeReference);
const elementType = typeArgs[0];

To check if a type is an array type, I usually just check the type's symbol's name for Array and if it has a single type argument.要检查类型是否为数组类型,我通常只检查Array的类型符号名称以及它是否具有单个类型参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM