函数参数类型取决于其他参数的类型 [英] Function parameter type depending on type of other parameter

查看:33
本文介绍了函数参数类型取决于其他参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个具有以下类型签名的函数:

I am trying to write a function which has the following type signature:

  • 参数 a 的类型为 stringundefined
  • 参数 bstring 如果 a 也是 string,否则它是 号码
  • parameter a is either of type string or undefined
  • parameter b is a string if a is also a string, otherwise it is a number

到目前为止,我的方法如下:

My approach up to now was the following:

function myFunction<X extends string | undefined>(
    a: X,
    b: X extends undefined ? number : string,
) {
    // ... do stuff ...
}

调用 myFunction 与预期的一样,即.myFunction('a', 'b') 起作用,而 myFunction(undefined, 'b') 抛出错误.但是,当我尝试使用函数体中的参数时,我没有任何类型支持:

Calling myFunction works just as expected, ie. myFunction('a', 'b') works while myFunction(undefined, 'b') throws an error. However, when I try to use the parameters in the function body, I don't have any typing support:

function myFunction<...>(...) {
    if (a !== undefined) {
        // a is a string -> b must also be a string
        b.split(''); // -> Property 'split' does not exist on type 'X'
    }
}

我是否必须在我的函数中进行强制转换,或者我能否以某种方式说服打字稿推断我的类型?

Do I have to cast inside my function or can I somehow convince typescript to infer my type?

完整的示例:的https://打字稿-play.js.org/#code/GYVwdgxgLglg9mABAWwJ4DFzXmAPADUQFMAPKIsAEwGdFqoAnGMAc0QB9FxKjhmjKAPgAUAKEQTEAQwBcifABpxkgEZzCpclVrde-SogD8iMCGQqiDRHPpNWSgJSIA3sokxgiYVMQBCALz+XFR6YAJOrpJRiAD0MdKIMLQ+tsxsALSCiCooIPTSADbUcNlECamsbtEqAHTUAA4FMFDCAOStDgDcVQC+oj1AA

推荐答案

Typescript 不支持基于另一个缩小参数.就编译器而言ab 是独立的,检查a 不会影响b 的类型即使条件类型在概念上将它们联系在一起.

Typescript does not support narrowing parameters one based on another. As far as the compiler is concerned a and b are independent and checking a will not impact the type of b even if the conditional type ties them together conceptually.

这篇关于函数参数类型取决于其他参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆