2

I've defined an interface A like this:

interface A {
  (): any;
  b: any;
};

However, it's not easy to define a variable that is compatible with this interface.

I've tried with:

var a: A = function () { console.log('This is a function'); }
a.b = 'This is a field';

This snippet failed due to Property 'b' is missing in type '() => void'. I think it's reasonable, as there's no b field when defining a.

Then I tried with this one:

var a: A = <A> function () { console.log('This is a function'); }
a.b = 'This is a field';

This worked, but I have no idea what's this <A> function ... syntax is.

It'll be great if someone could help. I've searched every corner in the official document.

Thanks.

1 Answer 1

2
var a: A = <A> function () ...

Here, <A> is not a generic, it's a cast (you could instead write as A at the end). The problem with your original statement (which was missing the cast) was that you were assigning something that had no property b to your variable a: A (a function, on its own, will satisfy only your (): any declaration). By casting, you are asserting that your function does (or will) have that property.

You could, alternatively, make b optional by defining it as:

b?: any;

In which case you would not need the cast, but I would say this is a mild abuse of the optional, which I think is better suited to options objects (used as parameters).

Note that it is bad practice to assign properties to functions in TypeScript (which is why you are running into difficulties), even though the language allows it (for the sake of converting old js).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer! Yes, I think this "function with properties"' style is quite confusing, but it did happen in some library like requireJS.

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.