2

Say I have this file foo.ts:

export const render = function ( a : Image, b : number ) : Image {
  // ...
}

How can I extract the type of "render" ?

I would like to end up with JSON like this:

{ "render": { "params": [ "Image", "number" ], "return": "Image" } }

Use case: I am building a tool where the user can visually connect elements of typescript code and I would like to cache the types of the "slots" so that I can show visually which connections are possible in advance.

2 Answers 2

2

I am building a tool where the user can visually connect elements of typescript code and I would like to cache the types of the "slots" so that I can show visually which connections are possible in advance.

You need to get a hold of the typechecker(what is it).

As a sample you can get display parts using a method exported by the npm typescript module :

https://github.com/TypeStrong/atom-typescript/blob/ae66fbbba503aaa2329209421f3362a35f89127c/lib/main/lang/fixmyts/quickFixes/extractVariable.ts#L179-L180

let type = typeChecker.getTypeAtLocation(node);
let typeSignature = ts.displayPartsToString(ts.typeToDisplayParts(typeChecker, type)).replace(/\s+/g, ' ');

That said I am writing a tool that can help other tool developers like you : http://alm.tools/

Sign up to request clarification or add additional context in comments.

Comments

0

There's no way to do that in typescript (as I'm aware).

What you run is javascript not typescript and all of the types aren't available in the compiled javascript code.

If you have the code as typescript, you can use the typescript compiler to build a syntax tree and then from that get what you want.
You can do that with node, probably using the typescript module itself but it might not be easy nor well documented, there's this typescript-compiler project (npm | github) but doesn't look like it's being maintained.

However, if you want to do that in the client alone then you might have a problem.
A short search popped out typescript-script and typescript-compile, but I haven't really looked into what those do and how, so I'm not sure if they can serve your purposes.


Edit

Here's another thought, you might save yourself a lot of trouble if you require the user to provide the .d.ts files along with the .ts files.
From that you can get the needed info, you'll have to start searching and comparing between the files, but that's different kind of trouble.

1 Comment

I am working on an editor so requiring a .d.ts file is not really an option. But I could produce the .d.ts file and regexp/scan this. I'll try this route if I cannot wrap my head around the compiler+checker...

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.