根据第一个参数的值将第二个参数定义为条件类型 [英] Defining second parameter as a conditional type based on the value of the first paramenter
本文介绍了根据第一个参数的值将第二个参数定义为条件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有两个参数的函数.我想根据第一个参数的值将第二个参数的类型设置为条件类型.这怎么可能
I have a function with two parameters. I want to set the type of the second parameter as a conditional type based on the value of the first parameter. How is this possible
这是示例代码:
type Event<T> = T extends 'string'? string : number;
function test(module:'string'|'number', event:Event<typeof module>)
{
//...
}
// The second argument is of type string | number
// But it should be string
test('string',2)
第二个参数的类型总是string|number
.
The second parameter is always of type string|number
.
推荐答案
你可以让你的函数通用来解决这个问题.
You can make your function generic to solve this issue.
function test<T extends string | number>(module: T, event: Event<T>) {
// ...
}
这篇关于根据第一个参数的值将第二个参数定义为条件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文