如何让一个类在 Typescript 中实现调用签名? [英] How to make a class implement a call signature in Typescript?

查看:74
本文介绍了如何让一个类在 Typescript 中实现调用签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在打字稿中定义了以下接口:

I have defined the following interface in typescript:

interface MyInterface {
    () : string;
}

这个接口简单地引入了一个不带参数并返回一个字符串的调用签名.如何在类中实现这种类型?我尝试了以下方法:

This interface simply introduces a call signature that takes no parameters and returns a string. How do I implement this type in a class? I have tried the following:

class MyType implements MyInterface {
    function () : string {
        return "Hello World.";
    }
}

编译器一直告诉我

类 'MyType' 声明了接口 'MyInterface' 但没有实现它:类型 'MyInterface' 需要调用签名,但类型 'MyType' 缺少一个

Class 'MyType' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a call signature, but Type 'MyType' lacks one

如何实现调用签名?

推荐答案

类无法匹配该接口.你能得到的最接近的是这个类,它将生成在功能上与接口匹配的代码(但不是根据编译器).

Classes can't match that interface. The closest you can get, I think is this class, which will generate code that functionally matches the interface (but not according to the compiler).

class MyType implements MyInterface {
  constructor {
    return "Hello";
  }
}
alert(MyType());

这将生成工作代码,但编译器会抱怨 MyType 不可调用,因为它具有签名 new() = 'string'(即使你用 new 调用它,它将返回一个对象).

This will generate working code, but the compiler will complain that MyType is not callable because it has the signature new() = 'string' (even though if you call it with new, it will return an object).

要创建与接口实际匹配的内容而编译器不会抱怨,您必须执行以下操作:

To create something that actally matches the interface without the compiler complaining, you'll have to do something like this:

var MyType = (() : MyInterface => {
  return function() { 
    return "Hello"; 
  }
})();
alert(MyType());

这篇关于如何让一个类在 Typescript 中实现调用签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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