I'm trying to get the value of a template literal type. I know I have to parse the source file for this. I am using ts-morph
right now which basically extends the programmatic API of the TypeScript compiler. But I am open to other options of how to get the value of template literal types.
Here is an example of what I am trying to do:
import { Project } from 'ts-morph'
const sourceFile = project.createSourceFile('source.ts', `
type Hello = 'hello'
`)
const typeAlias = sourceFile.addTypeAlias({
name: `MyTemplateLiteralType`,
type: '${Hello} world'
})
console.log(typeAlias.getType().getLiteralValue()) // "hello world"
Note the getLiteralValue()
does not work for template literals, but I am looking for something similar that does.
I found the solution. You cannot retrieve it from the return value of addTypeAlias
. Instead, I had to do:
sourceFile.getTypeAliasOrThrow('MyTemplateLiteralType').getType().getLiteralValue()