简体   繁体   English

打字稿。 正确键入依赖于同一对象文字中属性的函数参数

[英]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. 大概是通过更改handleTestArr函数定义。

Playground 操场

Unfortunately elegant solution like tuple types will not work here, typescript will jump to number|string instead of inferring based on src . 不幸的是,像元组类型这样的优雅解决方案在这里不起作用,打字稿将跳至number|string而不是基于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) 这是不理想的(至少我们不必像在3.0之前的Tyepscript的旧版本中那样为每个数量的参数定义重载)

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[]
    },

])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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