如何在打字稿中正确键入可更新的函数?

时间:2019-08-03 18:06:17

标签: typescript new-operator

我有这个测试用例,在没有任何类的情况下,它可以在ES5中完美运行:

Player1Drugs = new ObservableCollection<DrugInventoryItem>(World.Player1.DrugInventory);

如何在TypeScript中编写此代码?

在函数定义中添加let Foo = function() { this.bar = 'baz'; }; let foo = new Foo(); 之后,但仍然出现错误。

this

所以我尝试将函数强制转换为可更新的类型,但随后提示

let Foo = function(this: { bar: string }) { this.bar = 'baz'; };

let foo = new Foo();
//        ^^^^^^^^^
// 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.

接口语法也无济于事:

let Foo = function(this: { bar: string }) { this.bar = 'baz'; } as new() => { bar: string; };
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Conversion of type '(this: { bar: string; }) => void' to type 'new () => { bar: string; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
//   Type '(this: { bar: string; }) => void' provides no match for the signature 'new (): { bar: string; }'.

let foo = new Foo();

因此,似乎唯一的出路是先将函数强制转换为未知函数,然后再转换为可更新的类型。

let Foo = function(this: { bar: string }) { this.bar = 'baz'; } as { new(): { bar: string; } };
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Conversion of type '(this: { bar: string; }) => void' to type 'new () => { bar: string; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
//   Type '(this: { bar: string; }) => void' provides no match for the signature 'new (): { bar: string; }'.
let foo = new Foo();

在没有引入类开销的情况下,真的没有更简单的方法可以在TypeScript中键入此函数吗?

0 个答案:

没有答案