简体   繁体   English

在TypeScript中,泛型参数位于函数之前

[英]In TypeScript, generics parameter before function

I've defined an interface A like this: 我已经定义了这样的接口A

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' . 由于Property 'b' is missing in type '() => void'因此此代码段失败。 I think it's reasonable, as there's no b field when defining a . 我认为这是合理的,因为在定义a时没有b字段。

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. 这行得通,但我不知道这个<A> function ...是什么<A> function ...语法是什么。

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). 在这里, <A>不是泛型,而是强制类型转换(您可以在末尾写as A )。 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). 原始语句(缺少强制转换)的问题在于,您正在为变量a: A分配不带属性b a: A (一个函数仅满足(): any声明)。 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定义为以下选项来使其成为可选的:

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). 请注意,即使语言允许,为TypeScript中的函数分配属性也是错误的做法(这就是为什么您会遇到麻烦)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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