Skip to content

Instantly share code, notes, and snippets.

@thatcatcancode
Last active August 4, 2022 16:20
Show Gist options
  • Save thatcatcancode/681deac94d641d7e1fad309cf924c5a4 to your computer and use it in GitHub Desktop.
Save thatcatcancode/681deac94d641d7e1fad309cf924c5a4 to your computer and use it in GitHub Desktop.
An example of a morph that generates interfaces from classes.
import { Project } from 'ts-morph'
/**
* Get the scope of the NestJS project by specifying its tsconfig.
*/
const project = new Project({
tsConfigFilePath: 'tsconfig.json',
})
/**
* Get the types pkg file you created to house the new types.
*/
const typePkgFile = project.getSourceFile('./types-pkg/index.ts')
if (!typePkgFile) throw Error('Cannot find type package file.')
/**
* Extract interfaces from class models and add to the types pkg.
*/
const modelFiles = project.getSourceFiles(['./src/**/*.model.ts'])
modelFiles.forEach((file) => {
const classes = file.getClasses()
classes?.forEach((c) => {
const i = c.extractInterface()
typePkgFile.addInterface(i)
const newInterface = typePkgFile.getInterface(i.name)
if (!newInterface) return
newInterface.setIsExported(true)
})
})
project.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment