Skip to content

Instantly share code, notes, and snippets.

@igrek8
igrek8 / check-syntax.ts
Created June 26, 2023 07:19
TypeScript Compiler API: Check language syntax using string content
import ts from "typescript";
const code = `type A = string;`;
const sourceFile = ts.createSourceFile("source.ts", code, ts.ScriptTarget.Latest);
const host = ts.createCompilerHost({});
const getSourceFile = host.getSourceFile;
host.getSourceFile = function (name, languageVersion) {
return name === sourceFile.fileName ? sourceFile : getSourceFile.call(host, name, languageVersion);
};
const program = ts.createProgram([sourceFile.fileName], { noEmit: true }, host);
@igrek8
igrek8 / create-type-node-from-string.ts
Created June 26, 2023 07:21
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;
}
@igrek8
igrek8 / pack.ts
Created June 29, 2023 10:13
Pack and unpack JSON value
export function packJSON(object: unknown) {
const fragments: object[] = [];
const indices = new Map<string, number>();
function next(node: unknown): unknown {
if (node && typeof node === "object") {
let fragment: object;
if (Array.isArray(node)) {
fragment = node.map((el) => next(el));
} else {
fragment = Object.entries(node).reduce<Record<string, unknown>>((obj, [key, value]) => {