[英]TypeScript return different type based on type arguments
I have a function myFunc<T1, T2 = undefined>
that returns [T1]
if T2 extends undefined
else [T1, T2]
.我有一个函数
myFunc<T1, T2 = undefined>
如果T2 extends undefined
else [T1, T2]
则返回[T1]
[T1, T2]
。 Is it possible to make such a function without // @ts-ignore
?是否可以在没有
// @ts-ignore
情况下创建这样的函数?
function myFunc<T1, T2 = undefined>(t1: T1, t2?: T2): T2 extends undefined ? [T1] : [T1, T2] {
if (t2 === undefined) {
return [t1];
}
return [t1, t2];
}
This syntax gives me a TypeScript error on each return
statement, saying the value is not assignable to T2 extends undefined ? [T1] : [T1, T2]
这个语法在每个
return
语句上给我一个 TypeScript 错误,说值不能分配给T2 extends undefined ? [T1] : [T1, T2]
T2 extends undefined ? [T1] : [T1, T2]
. T2 extends undefined ? [T1] : [T1, T2]
。
Conditional types usually cause problems in the implementation.条件类型通常会在实现中引起问题。 You can't assign anything to a conditional type that still has unresolved type parameters except something of the exact same conditional type.
除了完全相同的条件类型之外,您不能为仍然具有未解析类型参数的条件类型分配任何内容。 So typescript will not let you assign
[T1]
or [T1, T2]
to the return value.所以打字稿不会让你将
[T1]
或[T1, T2]
分配给返回值。
You can use a type assertion, or you can use a separate implementation signature, one that returns a union.您可以使用类型断言,也可以使用单独的实现签名,即返回联合的签名。 I personally prefer this second option:
我个人更喜欢第二种选择:
function myFunc<T1, T2 = undefined>(t1: T1, t2?: T2): T2 extends undefined ? [T1] : [T1, T2]
function myFunc<T1, T2 = undefined>(t1: T1, t2?: T2): [T1] | [T1, T2] {
if (t2 === undefined) {
return [t1];
}
return [t1, t2];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.