简体   繁体   English

VSCode/TypeScript 中是否有“使用显式类型重构”?

[英]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.

相关问题 是否有 VSCode 扩展添加快速修复以将显式类型添加到 Typescript 的字段? - Is there a VSCode extension that adds a Quick Fix for adding the explicit type to a field for Typescript? 如何使用VSCode在非打字稿文件中使用类型定义 - How to use type definitions in non typescript files using VSCode 打字稿:使用类型进行显式导入 - Typescript: use types for explicit import VSCode 和 TypeScript - 重构/重命名而不打开受影响的文件 - VSCode and TypeScript - refactoring/renaming without opening the affected files Typescript vscode 重构:将类从文件移动到另一个(存在的)文件 - Typescript vscode refactoring: Move class from file to another (existent) file Typescript 导出推断类型而不是显式类型 - Typescript export inferred type instead of explicit type VSCode TypeScript intellisense 不是类型缩小 - VSCode TypeScript intellisense is not type narrowing VSCode 和 Typescript:“没有找到……的类型定义” - VSCode and Typescript: “No type definitions found for …” 重构打字稿云功能以使用承诺链 - Refactoring typescript cloud function to use promise chaining 在TypeScript中为导入的符号指定显式类型 - Specify explicit type for imported symbol in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM