0

I want to introspect a function at runtime and generate a ReturnType string similar to the hover functionality in VS Code. I know VS Code is just running a typescript server in the background so theoretically this should be possible.

import * as ts from "typescript"

I've already been able to import typescript and crawl the AST to grab the exact Node for the function declaration (although I'd like this to work for both arrow and regular functions).

example

const foo = () => ({ bar: "baz" }); // function.ts
getReturnType("function.ts","foo") // returns "{bar:string}"

One of many notable caveats is that the function may call other functions declared in different files and ideally the type string should resolve everything to primitives, i.e.,

type complex = {
  users: User[]
}

// what I want
type primitive = {
  users: { name: string; role: string }[]
}

VS Code example

VS Code example

1
  • Even vscode doesn't resolve that to primitives. This extension does something similar though: github.com/d-kimuson/ts-type-expand you can check out its source code. But the question, as it is currently stated, is quite broad for stackoverflow. Commented Dec 27, 2021 at 16:04

1 Answer 1

0

EDIT: Sorry, I missed the most important detail that you want your output to be actually a string representing the type. You may disregard the rest of the answer.

Have you seen template literal strings? I haven't really worked with them, but I saw this similar question and did some small adjustments (playground) to make it proper work in current TypeScript.

Does it makes sense for what you want to achieve? I may be being too simplistic here, but if I correctly understood your problem, you don't even need to actually manipulate typescript's AST

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.