简体   繁体   中英

In TypeScript, generics parameter before function

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM