简体   繁体   English

泛型类型为 function 返回类型

[英]Generic type as function return type

Say I have some code as below:假设我有一些代码如下:

function add<T extends boolean>(n1: number, n2: number, showResult: T): L<T> {
  if (showResult) {
    console.log(n1 + n2)
    return undefined // Type 'undefined' is not assignable to type 'L<T>'.(2322)
  } else {
    return n1 + n2 // Type 'number' is not assignable to type 'L<T>'.(2322)
  }
}

type L<G extends boolean> = G extends true ? undefined : number

type K = L<true> // K: undefined

const result = add(1, 2, false) // result: number

The add function returns type depends on showResult , so I introduce a generic type parameter T , and a generic type L . add function 返回类型取决于showResult ,所以我引入了泛型类型参数T和泛型类型L I'm a little confused about why there are two errors that indicate neither undefined nor number can assign to type L<T> .我有点困惑为什么有两个错误表明undefinednumber都不能分配给类型L<T>

How can I eliminate these errors while still have the benefit of inferring result type?我怎样才能消除这些错误,同时仍然可以推断result类型?

Thanks in advance.提前致谢。

Your type signature indicates that the caller can pass any type that extends boolean, and your function will return L parameterized of that type .您的类型签名表明调用者可以传递任何扩展 boolean 的类型,并且您的 function 将返回L parameterized of that type undefined is not " L parameterized by whatever type the caller passed, which extends boolean." undefined不是“ L由调用者传递的任何类型参数化,它扩展了 boolean。” (It is true that boolean is a bit magical here, and it may not be possible in practice to extend it, but your signature indicates that you expect it to be.) (的确,boolean在这里有点神奇,在实践中可能无法扩展它,但你的签名表明你期望它是。)

While I wouldn't particularly recommend this function at all (passing a boolean is often a sign of a design problem, and you really should just have two functions), if I were going to implement it I'd recommend overloads:虽然我根本不会特别推荐这个 function (传递 boolean 通常是设计问题的标志,你真的应该只有两个函数),如果我要实现它,我建议重载:

function add(n1: number, n2: number, showResult: true): undefined
function add(n1: number, n2: number, showResult: false): number
function add(n1: number, n2: number, showResult: boolean): number | undefined
{
    // Implementation
}

This says if you pass a boolean, it will return a number or undefined, but if it's known at compile time to be true, it will be undefined, and if it's known to be false, it will be a number.这表示如果你传递一个 boolean,它将返回一个数字或未定义,但如果它在编译时已知为真,它将是未定义的,如果已知为假,它将是一个数字。

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

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