函数参数类型取决于其他参数的类型 [英] Function parameter type depending on type of other parameter
问题描述
我正在尝试编写一个具有以下类型签名的函数:
I am trying to write a function which has the following type signature:
- 参数
a
的类型为string
或undefined
- 参数
b
是string
如果a
也是string
,否则它是号码
- parameter
a
is either of typestring
orundefined
- parameter
b
is astring
ifa
is also astring
, otherwise it is anumber
到目前为止,我的方法如下:
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?
推荐答案
Typescript 不支持基于另一个缩小参数.就编译器而言a
和b
是独立的,检查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屋!