Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

How to make a class implement a call signature in 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.";
    }
}

The compiler keeps telling me that

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

How can I implement the call signature?

question from:https://stackoverflow.com/questions/12769636/how-to-make-a-class-implement-a-call-signature-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...