在打字稿中返回泛型类型 [英] Generic Types Return in Typescript

查看:78
本文介绍了在打字稿中返回泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由cal()方法组成的接口find。
Class a1和a2实现接口。 a1返回一个数字,而a2返回字符串。我如何定义一个界面来解决我的问题。

I have a Interface find which consists of method cal(); Class a1 and a2 implements the interface. a1 returns a number while a2 returns string. How can i define a single interface to solve my issue.

以下是所提到的内容片段。

The below is having the snippet of what is mentioned.

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

推荐答案

您可以将接口设为通用的。

You can make the interface generic.

// 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的超集,具有一流的功能,使得代码变得非常丑陋和单一化。

TypeScript, as a superset of JavaScript, has first class functions which makes the code above pretty ugly and unidiomatic.

它简单地写一个函数会更好。

It would be much better to simply write a function.

function a1() {
  return "10";
}

function a2() {
  return 12;
}

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

Of course your actual code may be more complex, but if you have an interface with only one member, and if that member is a function, just use a function.

我也编辑了style的代码。具体来说,类型和类名都应该是 PascalCased

I also edited the code for style. Specifically, both type and class names should be PascalCased.

这篇关于在打字稿中返回泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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