![](/img/trans.png)
[英]Is there a VSCode extension that adds a Quick Fix for adding the explicit type to a field for Typescript?
[英]Is there a “use explicit type refactoring” in VSCode/TypeScript?
有沒有辦法可以將推斷類型的完整路徑復制到剪貼板?
例子:
class App { listen(){ const server = expressApp.listen()}}
我想讓server
成為成員而不是本地成員,但我不知道類型。 是否有 1 點擊獲取類型?
我認為 C# 有這個: https://docs.microsoft.com/en-us/visualstudio/ide/reference/convert-var-to-explicit-type?view=vs-2019
編輯:
要獲取 function 返回的類型,您可以使用ReturnType
類型構造函數。 將它與使用括號表示法的類型索引結合起來,您可以找到接口成員的返回類型,如下所示:
type Server = ReturnType<Express['listen']>;
Node 標准模塊http
公開了一個名為Server
的類型。 由於 Express 使用此類型作為其服務器偵聽器,因此您可以使用它在您的成員上鍵入偵聽器,如下所示:
import type { Express } from "express";
import type { Server } from "http";
class App {
constructor(app: Express) {
this.listener = app.listen();
}
private listener: Server;
}
如果您想像在上面的代碼片段中那樣使用帶有未初始化server
變量的自定義listen()
function,您只需將該屬性設為可選:
class App {
private server?: Server;
listen(expressApp: Express) {
this.server = expressApp.listen()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.