Skip to content

Instantly share code, notes, and snippets.

@igrek8
Created June 26, 2023 07:21
Show Gist options
  • Save igrek8/56c2d9c79414881bf191d100f143bd59 to your computer and use it in GitHub Desktop.
Save igrek8/56c2d9c79414881bf191d100f143bd59 to your computer and use it in GitHub Desktop.
TypeScript Compiler API: create a type node from a string
import assert from "assert";
import ts, { isTypeAliasDeclaration } from "typescript";
function createTypeNodeFromString(type: string): ts.TypeNode {
const sourceFile = ts.createSourceFile("source.ts", `type A = ${type};`, ts.ScriptTarget.Latest);
const statement = sourceFile.statements[0];
assert(isTypeAliasDeclaration(statement));
return statement.type;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment