[英]How to write typescript with constructor function/new keyword?
這是MDN 文檔中使用new
關鍵字的示例
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
我相信,function 的 TS 版本是:
/* car type */
type CarDetails = {
make: string;
model: string;
year: number;
}
/* setting this to type CarDetails */
function Car(this:CarDetails, make: string, model:string, year:number) {
this.make = make;
this.model = model;
this.year = year;
}
這在編寫方法時為我提供了智能感知/自動完成功能,但我如何在使用new
關鍵字創建實例時使 TS 推斷類型。 即使在對方法進行打字之后,創建一個這樣的實例:
const car1 = new Car('Eagle', 'Talon TSi', 1993);
仍然保持car1
為any
類型
car1
的類型推斷為Car
方法的this
類型? (沒有為實例 object 顯式設置類型,const car1: CarDetails = new Car(...;
)
顯然 class 語法應該是通往 go 的方式,但正如你一樣,我也在兜圈子,試圖找到輸出舊的有效 JS 語法的正確解決方案。 這是我在這個隨機答案中找到的一個很好的近似值,但在Typescript 官方文檔中對此解釋得很差。 這是我修改以使其更好的相關部分:
// Only instance members here.
export interface Circle { // Name the interface with the same than the var.
radius: number;
area: () => number;
perimeter: () => number;
}
// You could define static members here.
interface CircleConstructor {
new(radius: number): Circle;
}
export const Circle = function(this: Circle, radius: number) {
const pi = 3.14;
this.radius = radius;
this.area = function () {
return pi * radius * radius
}
this.perimeter = function () {
return 2 * pi * radius;
}
} as unknown /*as any*/ as CircleConstructor; // Note the trust-me casting
const c = new Circle(3); // okay
這帶來了一些問題。 例如,它正在使用any
被禁止的類型,或者必須使用as
操作符,這是非常丑陋的。 作為改進,我使用了unknown
而不是any
但核心問題仍然存在。 這使得 lint 工具不會報錯,所以它比any
有了很大的改進。
這是迄今為止我找到的最佳解決方案。 Typescript 開發人員意識到了這一點,但他們決定不為這種“語法”提供支持。
您可以改用類:
class Car { make: string; model: string; year: number; constructor(make: string, model: string, year: number) { this.make = make; this.model = model; this.year = year; } } // usage is the same const car1 = new Car('Eagle', 'Talon TSi', 1993);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.