如何在TypeScript中指定函数返回某个类型?

时间:2014-07-03 11:52:43

标签: typescript

假设我有以下要从TypeScript调用的第三方JavaScript函数:

function foo(obj) {
  var x = new obj.newable();
  x.bar();
}

以下是我的JavaScript代码(我想移植到打字稿):

foo({
  newable: function() {
    this.bar = function() {
      console.log("Hi");
    }
  }
});

这成功打印了#34; hi"。但现在我想将我的代码移植到TypeScript。特别是我想确保new obj.newable()返回的对象包含方法bar

我尝试了一些类似的事情:

interface IForFoo {
  newable: {new () : IWithBar};
}
interface IWithBar {
  bar: () => void;
}
function foo(obj: IForFoo) { // this will eventually be specified in a .t.ts file
  var x = new obj.newable();
  x.bar();
}

但这不起作用,因为Type 'new() => IWithBar' requires a construct signature, but type '() => void' lacks one。 (说实话,我还没弄清楚construct signature指的是什么。)

我如何得到这个"对"?

2 个答案:

答案 0 :(得分:2)

首先让它运作起来。

工作示例

以下是最简单的解决方案

interface Foo{
    newable:{
        () : {bar:Function}
    }
}

declare function foo(arg:Foo);

foo({
  newable: function() {
    this.bar = function() {
      console.log("Hi");
    }
    return this;
  }
});

告诉TypeScript新的

如果你想强制执行新的约束,即它必须适应new,你需要使用TypeScript类,即

interface Foo {
    newable: {
        new (): { bar: Function }
    }
}

declare function foo(arg: Foo);


class NewAble {
    bar = () => console.log('Hi');
}

foo({
    newable: NewAble
});

答案 1 :(得分:0)

稍微复杂的尝试

interface IForFoo {
    newable: () => IForBar
}

interface IForBar {
    bar: () => void
}


class Foo implements IForFoo {
    newable(): IForBar {
        return new Bar()
    }
}

class Bar {
    bar() {
        console.log('Hi')
    }
}

function foo(obj: typeof Foo) { // this will eventually be specified in a .t.ts file
    var x = (new obj).newable();
    x.bar();
}

foo(Foo)
相关问题