【问题标题】:Typescript conditional return type with default argument value具有默认参数值的打字稿条件返回类型
【发布时间】:2019-11-25 05:11:03
【问题描述】:

我正在尝试使函数根据参数值返回条件类型,但参数具有默认值:

function myFunc<T extends boolean>(myBoolean: T = true): T extends true 
       ? string 
       : number {
       return  myBoolean ? 'string' : 1
    }

这会引发错误Type 'true' is not assignable to type 'T'. 'true' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.

我不明白这个错误,因为T 是一个布尔值,为什么我不能将true 分配给它?

我尝试了另一种函数重载方法:

function myFunc(myBool: true): string
function myFunc(myBool: false): number
function myFunc(myBool = true) {
       return  myBool ? 'string' : 1
    }

myFunc()

但是现在打字稿不允许我在没有参数的情况下调用myFunc()(即使它有一个默认值)并且第一个重载有一个错误This overload signature is not compatible with its implementation signature.

是否有可能在打字稿中实现我想要实现的目标,如果儿子怎么做?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您的重载方法应该有效。您可以为true 重载设置可选参数:

    function myFunc(myBool?: true): string
    function myFunc(myBool: false): number
    function myFunc(myBool = true): string | number {
        return  myBool ? 'string' : 1
        }
    
    myFunc()
    

    【讨论】:

    • 工作就像一个魅力,我不知道我需要将我的论点声明为可选,感谢您的帮助!
    • 这是因为从外部看不到实现签名 - 即本例中的第三个 myFunc 声明(不是重载的声明)。所以 TS 只查看两个重载,并且没有?,不认为参数是可选的。更多信息:typescriptlang.org/docs/handbook/2/…
    【解决方案2】:

    T 不是boolean,它是boolean 的子类型。

    考虑一个更一般的例子:

    type T0 = { foo: string; };
    declare function useFoo<T extends foo>(arg: T = { foo: 'bar' });
    

    这也会失败,因为有效的 T 也可以是 { foo: string; bar: number; }T0 的子类型),默认参数不可分配给它。

    因此,默认参数和泛型通常不会同时使用,而且重载可能会更好,例如 Titian's answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2021-09-17
      • 1970-01-01
      • 2020-03-11
      • 2022-07-07
      • 1970-01-01
      • 2020-05-27
      相关资源
      最近更新 更多