第二个函数参数的条件类型 [英] Conditional type of second function argument
问题描述
我具有以下功能:
function doSomething(param1: string, param2: string) {
return param1 + param2;
}
我也有基于json的类型,其结构类似于此:
also I have json based type with structure looking similar to this:
a1: {
b1: 'something1',
b2: 'something2',
b3: 'something3'
},
a2: {
c1: 'something4',
c2: 'something5'
}
...etc
我希望提到的函数的第n个参数为第n个深层元素的文字,因此如果第一个参数为'a1'
,则第二个应为'b1' | 'b2' | 'b3'
,如果第一个参数为'a2'
,则第二个应为'c1' | 'c2'
.
I want nth argument of mentioned function to be literal of nth deep elements, so if first argument is 'a1'
, second should be 'b1' | 'b2' | 'b3'
, and if first argument is 'a2'
, second should be 'c1' | 'c2'
.
对于第一个参数,我已经做了简单的keyof typeof data
类型,该类型很好用:
For first argument I've made simple keyof typeof data
type, which is working great:
// data is imported json
type FirstArg = keyof typeof data;
我第二次尝试这样的通用类型,但没有成功:
For second I was trying generic type like this, but without success:
type SecondArg<T extends FirstArg> = keyof typeof data[T];
有机会这样做吗?
推荐答案
对于任何数量的参数,您都无法做到这一点,您可以为特定深度定义重载:
You can't do it for any number of arguments, you can define overloads for up to a specific depth:
const data = {
a1: {
b1: 'something1',
b2: 'something2',
b3: 'something3'
},
a2: {
c1: 'something4',
c2: 'something5'
}
}
type DataType = typeof data;
function doSomething<K extends keyof DataType, K2 extends keyof DataType[K]>(p1: K, p2: K2, p3: keyof DataType[K][K2]): string
function doSomething<K extends keyof DataType>(p1: K, p2: keyof DataType[K]): string
function doSomething(p1: keyof DataType): string
function doSomething(...keys: PropertyKey[]) {
return keys.join('.');
}
doSomething("a1", "b1")
doSomething("a1", "c2") // err
这篇关于第二个函数参数的条件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!