0

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.

1 Answer 1

1

I found the solution. You cannot retrieve it from the return value of addTypeAlias. Instead, I had to do:

sourceFile.getTypeAliasOrThrow('MyTemplateLiteralType').getType().getLiteralValue()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.