简体   繁体   English

为什么 TypeScript 条件类型对于可选参数不能正常工作?

[英]why TypeScript condition type can't work correctly for optional parameter?

i want to know wheather function's first args is optional, so i write this:我想知道函数的第一个参数是可选的,所以我写了这个:

type F1 = (payload?: number) => null;
type Res1 = F1 extends (a?: any) => any ? 1 : 2; // got 1
type Res2 = F1 extends (a: any) => any ? 1 : 2; // got 1, but 2 expected

type F2 = (payload: number) => null;
type Res3 = F2 extends (a?: any) => any ? 1 : 2; // got 1, but 2 expected
type Res4 = F2 extends (a: any) => any ? 1 : 2; // got 1

ALL OF THEM are both equl to 1 , why?它们都等于1 ,为什么? and how do i do?我该怎么做?

You can read 'extends' as 'is assignable to'.您可以将“扩展”阅读为“可分配给”。

type F1 = (payload?: number) => null;
type Res2 = F1 extends (a: any) => any ? 1 : 2; // got 1, but 2 expected

Is (payload?: number) => null assignable to (a: any) => any ? (payload?: number) => null分配给(a: any) => any吗? Let's check:让我们检查:

// Works
const res2: (a: any) => any = (payload?: number) => null;

(a: any) => any accepts any value for a , including undefined or a number as specified by payload, so we can see that (payload?: number) => null is assignable and therefore F1 extends (a: any) => any should evaluate to true and return 1. (a: any) => any接受a任何值,包括 undefined 或有效负载指定的数字,因此我们可以看到(payload?: number) => null是可分配的,因此F1 extends (a: any) => any应该评估为 true 并返回 1。

Instead, you can make the arguments of your function to test optional using Partial, and check if the resulting arguments are assignable to the original arguments:相反,您可以使用 Partial 使 function 的 arguments 测试可选,并检查生成的 arguments 是否可分配给原始 ZDBC11CAABD8BDA99F77E6FB4DABD882E7DZ


type ArgumentType<F extends (...args: any) => any> = F extends (...args: infer A) => any ? A : never;

type FirstArgumentOptional<F extends (...args: any) => any> =
    Partial<ArgumentType<F>> extends ArgumentType<F>
        ? true 
        : false


type T1 = FirstArgumentOptional<(a: any) => any>; // false
type T2 = FirstArgumentOptional<(a?: any) => any>; // true
type T3 = FirstArgumentOptional<() => any>; // true

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

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