简体   繁体   中英

Typescript. Correctly typing function parameter that depends on property in the same object literal

I have types where one depends on another:

type source = string | number;
type derivative<T extends source> = T extends string ? string[] : number[];

I can use them in function arguments and get correct inference:

在此处输入图片说明

Now I want to use them in interface:

interface Test<T extends source> {
    src: T;
    handler: (dvr: derivative<T>) => void;
}

Again I can use it as function input and get right types:

在此处输入图片说明

But if I need to pass several tasks, typescript can't infer right type:

在此处输入图片说明

Is it possible to fix this? Presumably by changing handleTestArr function definition.

Playground

Unfortunately elegant solution like tuple types will not work here, typescript will jump to number|string instead of inferring based on src .

The simplest solution is use a tuple parameter (with optional members) and several type parameters for each member of the tuple. This is not ideal (at least we don't have to define an overload for each number of parameters as we did in older versions of Tyepscript before 3.0)

function handleTestArr<
    T extends source,
    T1 extends source,
    T2 extends source,
    T3 extends source,
    T4 extends source,
    T5 extends source,
    T6 extends source,>(ts: [Test<T>, Test<T1>?, Test<T2>?, Test<T3>?, Test<T4>?, Test<T5>?, Test<T6>?])   
function handleTestArr(ts: Test<source>[]) {
}
handleTestArr([
    {
        src: 1,
        handler: x => {}, // x is number[]
    },{
        src: '1',
        handler: x => {}, // x is string[]
    },

])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM