nickf
nickf

Reputation: 546025

Type-check a string of TypeScript code

My situation:

What I've done so far:

I have a program which generates some TypeScript code, basically pulling data from the api and then seeing if the TypeScript compiler agrees that it matches the interface.

The result in the end looks something like:

import { User } from './user';

function verify<T>(data: T) {}

verify<User>({ id: 123, name: 'Joe' });
verify<User>({ id: 123, name: 17 }); // <-- obviously, this should give an error

Generating this code is all done, however I now need to get the compiler to type check it. I've been digging about in the typescript compiler API for a while and keep getting stuck because all of the functions which seem to do what I need all take a file name (ie: a path on disk) rather than a string of code. I understand that because of references to other files, there needs to be a path associated with the code, but I can't find any way to pass that in.

I'd like to avoid having to write these files to disk because

a) it seems a bit silly, since it's just going to be read from the disk then
b) it will likely get pretty messy in the source files, or I'd have to put it in a separate folder and then also rewrite all the import statements.

The TL;DR of my question is:

Is there a way to type-check a string of TypeScript code?

Upvotes: 0

Views: 1090

Answers (1)

basarat
basarat

Reputation: 275799

Two solutions

Don't have to write the js to disk just to run ts

I'd like to avoid having to write these files to disk because

You can use ts-node : https://github.com/TypeStrong/ts-node

Check a string of js

A string of JS is easy to check. Just use ts.transpile from the compiler API. That said ... you don't want to check just a string of js. You want to check a set of files. Hence recommend just using ts-node.

Upvotes: 1

Related Questions