如何使旧样式类在打字稿中工作? [英] How can I make old style classes work in typescript?

查看:84
本文介绍了如何使旧样式类在打字稿中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将大量文件转换为打字稿时,我有许多这样声明的类。

While converting a large number of files to typescript, I have many classes declared this way.

function FooClass() {
    this.bar = 1; // error TS2683: 'this' implicitly has type 'any'
                  // because it does not have a type annotation.
}

FooClass.prototype.myMethod = function() {
    // ...
}

如何启用严格的类型检查,同时又避免使用类语法将其全部重写?

How can I make this work with strict type checking turned on, while avoiding rewriting it all using class syntax?

推荐答案

使以上代码正常工作的最简单方法是添加对该功能的 this 参数,如下所示:

The easiest way to get the above code to work is to add a this parameter to the function, like so:

function FooClass(this: {bar: number}) {
    this.bar = 1; // okay
}

不幸的是,您很快就会发现编译器不知道当像对待构造函数那样对待 FooClass 时该怎么做:

Unfortunately, you will soon find that the compiler doesn't know what to make of FooClass when you treat it like a constructor:

const oops = new FooClass(); // error, oops is implicitly any
oops.bar // okay but compiler has no idea
oops.myMethod() // okay but also no idea
oops.foo // also okay, but you probably don't want it to be
oops.yourMethod() // ditto

这显然是设计。我认为,对此进行注释的最好方法是预先定义类型 FooClass FooConstructor

This is apparently by design. The best way to annotate this, in my opinion, is to define the types FooClass and FooConstructor in advance:

interface FooClass {
  bar: number;
  myMethod(): void;
}

interface FooConstructor {
  new(): FooClass,
  prototype: FooClass
}

请注意,当您使用 class FooClass {} 创建构造函数的方式时,TypeScript会自动生成两个 value FooClass 是构造函数本身,以及 type FooClass 这是构造函数创建的实例的类型。这通常会使开发人员感到困惑,因此请当心。我们在这里手动进行操作:上面的接口FooClass 类型,而不是 value

Note that when you use the class FooClass {} way of creating constructors, TypeScript automatically generates both a value FooClass which is the constructor itself, and a type FooClass which is the type of the instances created by the constructor. This is often confusing to developers, so take care. We are doing that here manually: the above interface FooClass is the type, not the value, which we are about to create.

定义这些类型之后,断言 FooClass 函数的类型为 FooConstructor 创建时(断言需要通过 Function any 和是不安全的,所以要小心)。

After you define those types, assert that the FooClass function is of type FooConstructor when you create it (the assertion needs to pass though Function or any and is not safe, so be careful).

const FooClass = function FooClass(this: FooClass) {
  this.bar = 1;
} as Function as FooConstructor;

FooClass.prototype.myMethod = function () {
  // ...
}

并对其进行测试:

const okay = new FooClass();
okay.bar // number
okay.myMethod() // known
okay.foo // error, yay
okay.yourMethod() // error, yay

希望有帮助;祝你好运!

Hope that helps; good luck!

这篇关于如何使旧样式类在打字稿中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆