[英]Typescript generics return type
I am new to typescript and I am trying to wrap my head around how generics work.我是打字稿的新手,我正试图围绕泛型的工作原理进行思考。 I am wondering why the following code doesn't fly:
我想知道为什么下面的代码不飞:
function identity<T>(arg: T): T {
let num: number = 2;
return num;
}
let output = identity<number>(1);
I get the error: Type 'number' is not assignable to type 'T'.我收到错误消息:“数字”类型不可分配给“T”类型。 If the input to the function is a number, does this not mean that the return type of number should work as well, since we are saying that T is of type number?
如果函数的输入是数字,这是否意味着 number 的返回类型也应该起作用,因为我们说 T 是数字类型?
You have to treat T
like any type in existence.你必须像对待现有的任何类型一样对待
T
Your function head says: I want an argument of type T and return something of type T.你的函数负责人说:我想要一个 T 类型的参数并返回 T 类型的东西。
Your code however always returns a number
, which does not have to be T
.但是,您的代码始终返回一个
number
,该number
不必是T
In your example call it is, but you could call it with identity<string>("test")
and expect a string to come back, but it would still be a number
.在您的示例中调用它,但您可以使用
identity<string>("test")
调用它并期望返回一个字符串,但它仍然是一个number
。 Thus the confict.冲突由此而来。
Let's have a look at the type signature of your identity function.让我们看看你的身份函数的类型签名。
function identity<T>(arg: T)
What we are saying here is that this function acceps an argument of type T
(which we are not specifying in advance, it could be anything), and it return a value of type T
.我们在这里说的是这个函数接受一个
T
类型的参数(我们没有提前指定,它可以是任何东西),并且它返回一个T
类型的值。
Given that there is no information whatsoever about T
, the only the function can return a value of such type is to reuse the provided argument.鉴于没有关于
T
任何信息,唯一可以返回这种类型值的函数是重用提供的参数。 In other words, there is exactly one and only one possible implementation of the identity function - the one that returns its argument.换句话说,恒等函数只有一种且只有一种可能的实现——返回其参数的实现。
function identity<T>(arg: T) { return arg }
The error message is telling you exactly this: Type 'number' is not assignable to type 'T'
, which is true because T
is, well, generic :)错误消息准确地告诉您:
Type 'number' is not assignable to type 'T'
,这是正确的,因为T
是通用的 :)
Short story , you should correct your function like this:短篇小说,你应该像这样更正你的功能:
function identity<T>(arg: T): T {
let num: T = arg;
return num;
}
let output = identity<number>(1)
console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.