Skip to content

yekezz/ts-type-to-code

Repository files navigation

ts-type-to-code

NPM version

Features

  • Based on AST, the object containing the key value is extracted from the typescript type, and the corresponding code is generated.

Resolve

I want to get the code of the configuration item from the type file, but I don't need json schema. returned. If option is false, the result will only return the required key.

Usage

pnpm add ts-type-to-code

// marker.d.ts
interface Marker {
  id: string
  off: Function
  on: Function
  options: MarkerOptions
}

interface MarkerOptions {
  map: Map
  position: number[]
  icon?: string
  animate?: boolean
}
import { tsTypeToCode } from 'ts-type-to-code'
tsTypeToCode('test/marker.d.ts', 'test/marker.ts', {optional: false})

from to

API

  • tsTypeToCode(srcPath: string, targetPath: string[, options: TsTypeToCodeOptions])

Options

  • optional: The default optional is true, which means that regardless of whether the key in the type is optional or not, it will be returned. If option is false, the result will only return the required key.

  • filter: filter the code on demand, or ignore it.

  • generate: methods for generating target file content. By default, it will be generated in the form of object(as above image).

interface TsTypeToCodeOptions {
  /**
   * Whether to keep the optional key
   */
  optional?: boolean
  /**
   * filter traverseCode
   */
  filter?: TraverseFilter
  /**
   * methods for generating target file content
   */
  generate?: GenerateMethod
}

Explain

The plugin only extracts codes for simple interface, and does not include complex ts types. Because ast's analysis of complex types is not very clear, in order to reduce complexity, there is a trade-off.

License

MIT License © 2022 Enoch

About

Based on ast, extract object from typescript type.

Resources

License

Stars

Watchers

Forks

Packages

No packages published