打字稿中的泛型类型返回

时间:2017-05-19 05:59:50

标签: generics typescript

我有一个Interface find,它包含方法cal(); 类a1和a2实现接口。 a1返回一个数字,而a2返回一个数字。如何定义单个界面来解决我的问题。

以下是上述内容的摘要。

interface Ifind {
    cal() : string;
}

class a1 implements Ifind{

    public cal():string{
        return "10";
    }
}

class a2 implements Ifind{
    public cal(): number{
        return 12;
    }
}

class main{
    private obj;

    constructor() {
        this.obj = new a1();
        var p = this.obj.cal();
        alert(p)
    }
}

in TypeScript Playground

1 个答案:

答案 0 :(得分:5)

您可以使界面通用。

// Edited for naming   
interface Find<T> {
    cal() : T;
}

class A1 implements Find<string> {
    cal(): string {
        return "10";
    }
}

class A2 implements Find<number> {
    cal(): number {
        return 12;
    }
}

对上述代码的一些评论。

TypeScript作为JavaScript的超集,具有一流的功能,使得上面的代码非常丑陋而且非常简单。

简单地写一个函数会好得多。

function a1() {
  return "10";
}

function a2() {
  return 12;
}

当然,您的实际代码可能更复杂,但如果您的接口只有一个成员,并且该成员是函数,则只需使用函数。

我还编辑了样式代码。具体来说,类型和类名都应该是 PascalCased

相关问题