2

I need to implement the following (simplified) Typescript Interface of an d.ts file:

interface SomeLibrary {
    someProperty: SomePropertyClass;
    someMethod();
    (someParam: string): SomeClass; // don't know hot to implement this
}

How do I implement this interface in an own class? Especially the unnamed method is problematic. How are those methods called?

1

1 Answer 1

2

The interface you have shown can't be satisfied by a class in TypeScript.

Interfaces like this are usually created to describe a library that uses a different pattern.

One example of how you can satisfy the interface is shown below:

var example: SomeLibrary = <any> function(someParam: string) {
    console.log('function called');
    return new SomeClass();
}
example.someProperty = new SomePropertyClass();
example.someMethod = function () { console.log('method called'); };

var x = example('x');
var y = example.someProperty;
var z = example.someMethod();
Sign up to request clarification or add additional context in comments.

4 Comments

What does the <any> in this example mean?
The function in that expression doesn't actually satisfy the interface (because it is missing the someProperty and someMethod members). For this reason, you need to wiggle the type to tell the compiler I know that this type will be okay, even though it doesn't look like it is to you. If you forgot to add the next two lines, you'd cause a runtime problem though!
Is it a cast to the any type?
Yes - a type assertion that widens the function to any, so it can then be narrowed by the preceding SomeLibrary type annotation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.