【问题标题】:TypeScript Compiler API: get type structureTypeScript Compiler API:获取类型结构
【发布时间】:2021-08-02 23:08:55
【问题描述】:

是否有 API 方法可以从 TypeScript 编译器获取“触底”类型信息?示例:

interface User {
  id: number
  name: string
}

type NameOnly = Pick<User, 'name'>

type NameOnlyAliased = NameOnly

在 VSCode 中,如果我将鼠标悬停在 NameOnlyAliased 上,它会显示:

type NameOnlyAliased = {
    name: string;
}

我的问题是编译器 API 中是否有一个函数(或其他不应用别名语义的简单方法,Pick 等)来获取上面= 右侧的信息,最好作为数据(不仅仅是字符串),例如:

{
  NameAliasedOnly: {
    properties: {
      name: {
         type: 'string'
      }
    }
  }
}

用例是生成代码以根据类型定义创建fast-check 任意值(如果已经存在,那就太棒了)。为此,我使用ts-json-schema-generator 进行了一些尝试,但有些类型定义它无法处理。

【问题讨论】:

  • 您能说明一下您的用例吗?可能有人提供的答案不能回答您的确切问题,但确实可以解决您的问题。我的意思是,也许有一种方法可以做任何你需要做的事情,但不能用这种确切的方法来完成。

标签: typescript typescript-compiler-api


【解决方案1】:

我找到了解决方案。它不直接使用 TypeScript 编译器 API,而是使用出色的 ts-morph library,它是编译器 API 的包装器,可简化许多任务。这是一些示例代码,其中test.ts 文件包含我上面问题中的示例代码。

import { Project, TypeFormatFlags } from 'ts-morph'

const project = new Project({
  tsConfigFilePath: 'tsconfig.json',
  skipAddingFilesFromTsConfig: true,
})
const file = 'test.ts'
project.addSourceFileAtPath(file)

const sourceFile = project.getSourceFile(file)

const typeAlias = sourceFile?.getTypeAlias('NameOnlyAliased')
if (typeAlias) {
  console.log(
    typeAlias
      .getType()
      .getProperties()
      .map(p => [
        p.getName(),
        p
          .getTypeAtLocation(typeAlias)
          .getText(
            undefined,
            TypeFormatFlags.UseAliasDefinedOutsideCurrentScope
          ),
      ])
  )
}

执行此脚本会根据需要输出[ [ 'name', 'string' ] ]。对于更复杂的类型,您可以导航到类型层次结构中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2021-05-12
    • 2021-02-21
    相关资源
    最近更新 更多