打字稿:对函数的“新”调用

时间:2021-03-07 17:21:31

标签: javascript typescript new-operator

最近我想把我的一个副项目转换成 Typescript。但是我无法使用 new 调用函数。

我正在尝试调用从另一个文件导入的函数,如下所示:

// Function in 'file.js'
function Foo() {
  this.x = 1;
  this.y = 2;
}
Foo.prototype.set = function() {
   return this.x + this.y;
};
export { Foo };
// Function in another file calling Foo
import { Foo } from './file';
function getSum() {
  let foo = new Foo(); // I got the below error here!!!
  foo.set();
}

当我尝试输入时,出现以下错误:'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.


typescript documentation,我明白调用签名应该写成这样:

type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

但我不知道如何将上述类型应用于我的 'Foo' 函数。 我尝试将构造签名应用于函数,但无法正确放置。

// Function in 'file.js' --> renamed to 'file.tsx'
type FooType = {
  x: number,
  y: number,
};

type FooConstructor = {
  new (): FooType
};

function Foo(this: FooType) { // How do I add FooConstructor to this?
  this.x = 1;
  this.y = 2;
}
Foo.prototype.set = function(): number {
   return this.x + this.y;
};

我无法在导出/导入或函数调用期间应用它。以下所有都抛出错误。

export { Foo: FooConstructor };
import { Foo: FooConstructor } from './file';
let foo = new Foo() as FooConstructor;

那么我是否应该将 Foo 函数更改为一个类,这是唯一可能的输入方式吗?!我看到很多博客展示了如何键入类。但即使采用这种方法,我还是收到了一条错误消息:Type 'FooType' is not assignable to type 'FooConstructor'

我迷路了。任何帮助表示赞赏!


编辑:我的 File.ts 现在看起来像这样:

我在 File.ts 文件中添加声明,如下所示:

type FooType = {
  x: number,
  y: number,
};

declare class Foo {
  constructor();
  x: number;
  y: number;
  setHeader(): number;
}

function Foo(this: FooType) {
  this.x = 1;
  this.y = 2;
}
Foo.prototype.set = function(): number {
   return this.x + this.y;
};

export { Foo };
```

3 个答案:

答案 0 :(得分:0)

在 .d.ts 文件中或直接在 .ts 文件中:

declare class Foo {
    public x: number;
    public y: number;

    set(): number;
}

Playground

答案 1 :(得分:0)

解决这种情况的唯一方法是将以下函数转换为类:

function Foo(this: FooType) { // How do I add FooConstructor to this?
  this.x = 1;
  this.y = 2;
}
Foo.prototype.set = function(): number {
   return this.x + this.y;
};

到:

class Foo() {
  x: number;
  y: number;
  constructor() {
    this.x = 1;
    this.y = 2;
  }
  set (): number {
   return this.x + this.y;
  }
}

答案 2 :(得分:0)

>Adjunto mi código espero ayude
>Para ejecutar solo realice new Functions() 
>para llamar a la clase internamente se ejecutar
> el constructor de Functions

type SomeConstructor = {
  new (s:string):SomeObject;
}


type SomeObject = any;


export class Example{
   constructor(s:string){
     console.log(s)
   }
}


 export class Functions {
    constructor(){
      const callable = (someObject:SomeObject)=>{
        return someObject;
      }

      this.fnSomeConstructor(callable(new Example("Hola")));
    }

   fnSomeConstructor(ctor: SomeConstructor) {
    return new func(func.name);
   }
 }
相关问题