Conditional type of second function argument

后端 未结 1 1518
有刺的猬
有刺的猬 2021-01-22 01:11

I have following function:

function doSomething(param1: string, param2: string) {
  return param1 + param2;
}

also I have json based type with

相关标签:
1条回答
  • 2021-01-22 01:59

    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
    
    0 讨论(0)
提交回复
热议问题