[英]Is there a “use explicit type refactoring” in VSCode/TypeScript?
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.我想让
server
成为成员而不是本地成员,但我不知道类型。 Is there 1 click to get type?是否有 1 点击获取类型?
I think C# has this: https://docs.microsoft.com/en-us/visualstudio/ide/reference/convert-var-to-explicit-type?view=vs-2019我认为 C# 有这个: https://docs.microsoft.com/en-us/visualstudio/ide/reference/convert-var-to-explicit-type?view=vs-2019
EDIT:编辑:
To get the types of a function return you can use the ReturnType
type constructor.要获取 function 返回的类型,您可以使用
ReturnType
类型构造函数。 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
. Node 标准模块
http
公开了一个名为Server
的类型。 Since Express uses this type for its server listeners, you can use it to type the listener on your member like so:由于 Express 使用此类型作为其服务器侦听器,因此您可以使用它在您的成员上键入侦听器,如下所示:
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:如果您想像在上面的代码片段中那样使用带有未初始化
server
变量的自定义listen()
function,您只需将该属性设为可选:
class App {
private server?: Server;
listen(expressApp: Express) {
this.server = expressApp.listen()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.