简体   繁体   English

TypeScript 根据类型参数返回不同的类型

[英]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.

相关问题 Typescript:基于 arguments 道具的条件返回类型 - Typescript: Conditional return type based on arguments props Typescript 基于arguments的动态联合返回类型 - Typescript dynamic union return type based on arguments Typescript 函数根据可选参数返回类型 - Typescript function return type based on optional arguments 如何基于参数中的函数返回类型指定打字稿条件类型 - How to specify typescript conditional type based on a function return type in the arguments 如何根据Typescript中的输入arguments改变函数返回类型? - How to change functions return type based on the input arguments in Typescript? 根据 TypeScript 中可区分联合的参数自动推断返回类型 - Automatically infer return type based on arguments for discriminated union in TypeScript 在TypeScript中,如何根据其参数之一的返回类型来确定函数的返回类型? - In TypeScript, how do I make a function's return type based on the return type of one of its arguments? 我如何让 typescript 根据 function2E977777777777777777777777777777777777777777777777777777777777777777777777777777777777BED18 的返回类型 functionC17A94F14Z 的返回类型来推断 function 的返回类型 - How do I get typescript to infer the return type of a function based on the return type on a function of its arguments 基于参数的推断返回类型 - inference return type based on arguments 基于 arguments 的显式返回类型 - Explicit return type based on arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM