2

Is there a way I can copy to clipboard the full path of an inferred type?

Example:

class App { listen(){ const server = expressApp.listen()}}

I want to make server a member and not a local, but I don't know the type. Is there 1 click to get type?

I think C# has this: https://learn.microsoft.com/en-us/visualstudio/ide/reference/convert-var-to-explicit-type?view=vs-2019

1 Answer 1

2

EDIT:

To get the types of a function return you can use the ReturnType type constructor. Combine that with type indexing using bracket notation and you can find the return type of an interface member like so:

type Server = ReturnType<Express['listen']>;

The Node standard module http exposes a type called Server. Since Express uses this type for its server listeners, you can use it to type the listener on your member like so:

import type { Express } from "express";
import type { Server } from "http";

class App {
  constructor(app: Express) {
    this.listener = app.listen();
  }
  private listener: Server;
}

If you want to use a custom listen() function with an uninitialized server variable as you're doing in your above code snippet, you just need to make the property optional:

class App {
  private server?: Server;
  listen(expressApp: Express) {
    this.server = expressApp.listen()
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! You are absolutely correct that this solves the specific case. But I often run into this general problem, and so am looking for a faster method to solve this than my current method (which is "Go to Type Definition", and then manually figure out an import strategy to that definition). TypeScript clearly has the import path figured out, so I'd love it if it would share with me ;)
Ah I see, yeah that would be nice 😅 I never even considered that there was an easier way to do it. Updating my answer (it's not pretty but it works)

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.