带有默认参数值的打字稿条件返回类型

Lak*_*ton 7 typescript

我试图让函数根据参数值返回一个条件类型,但参数的默认值是:

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

这会引发错误 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()
Run Code Online (Sandbox Code Playgroud)

但是现在打字稿不会让我不myFunc()带参数地调用(即使它具有默认值)并且第一个重载有错误This overload signature is not compatible with its implementation signature.

甚至有可能在打字稿中做我想要实现的目标,如果儿子如何?

Tit*_*mir 14

你的超载方法应该有效。您可以使该参数对于true重载是可选的:

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

myFunc()
Run Code Online (Sandbox Code Playgroud)