打字稿,自动从对象键推断类型

时间:2021-05-03 15:58:24

标签: typescript

我想为 Select 组件声明一个接口,该接口可以是多项或单项选择。

interface MySelect<T extends boolean> {
    multi: T, // Is this a multiple items select
    onChange: (item: T extends true ? string[]: string) => void // the onChange signature differs according to T
}

它有效,但我必须显式设置泛型类型 T:

const mySelect: MySelect<true> = { // Here
    multi: true, // And here
    onChange: (items) => {}
}

我想知道是否有可能让 TS 从“multi”值中自动推断出 T:

const mySelect: MySelect = {
    multi: true, // multi is true so T is true
    onChange: (items) => {}
}

重要更新:我希望“multiple”是可选的(如果键丢失或未定义,它将默认为 false)

2 个答案:

答案 0 :(得分:5)

您已经更新了您的问题,说明 multi 应该是可选的(默认为 false)。这排除了受歧视的联合(下方水平线下的先前答案)。

我想我会使用两个你联合在一起的接口,并且(如果有必要)一个基本接口来处理它们的共同点。当您需要知道选择的类型时,您可能需要类型保护函数。

// Things all MySelects have in common (if you have anything other than `onChange`)
interface MySelectBase {
    name: string;
}
// A single-select version of MySelect
interface MySingleSelect extends MySelectBase {
    multi?: false;
    onChange: (item: string) => void;
}
// A multi-select version of MySelect
interface MyMultiSelect extends MySelectBase {
    multi: true;
    onChange: (items: string[]) => void;
}
// The unified type
type MySelect = MySingleSelect | MyMultiSelect;

// Type guard function to see whether it's a single select
const isSingleSelect = (select: MySelect): select is MySingleSelect => {
    return !select.multi; // !undefined and !false are both true
};

// Type guard function to see whether it's a multi select
const isMultiSelect = (select: MySelect): select is MyMultiSelect => {
    return !!select.multi; // !!undefined and !!true are both true
};

创建示例:

const single: MySingleSelect = {
    name: "some-single-select-field",
    onChange : (item) => { console.log(item); }
};

const multi: MyMultiSelect = {
    multi: true,
    name: "some-multi-select-field",
    onChange : (items) => { console.log(items); }
};

使用MySelect(组合接口)的示例:

const useMySelect = (select: MySelect) => {
    // No need for a guard on anything but `onChange`
    console.log(select.name);
    // `onChange` will be a union type until/unless you use a type guard
    const onChange = select.onChange;
    //    ^^^^^^^^−−−−−−−−−− type is `((item: string) => void) | ((items: string[]) => void)`
    if (isSingleSelect(select)) {
        // It's a MySingleSelect
        const onChange = select.onChange;
        //    ^^^^^^^^−−−−−−−−−− type is `(item: string) => void`
    } else {
        // It's a MyMultiSelect
        const onChange = select.onChange;
        //    ^^^^^^^^−−−−−−−−−− type is `(items: string[]) => void`
    }
};

Playground link


这是不要求将 multi 设为可选的人的原始答案:

您可以通过将 MySelect 声明为类型的联合来实现这一点,一个带有 multi: true,另一个带有 multi: false

type MySelect =
    {
        multi: true;
        onChange: (items: string[]) => void;
    }
    |
    {
        multi: false;
        onChange: (item: string) => void;
    };

然后你得到:

const mySelect: MySelect = {
    multi: true,
    onChange: (items) => {}
//  ^^^^^^^^−−−−−−−−−−− correctly inferred as (items: string[]) => void
};

Playground link

这称为 discriminated union:由一个(或多个)字段的类型区分(区分)的类型的联合。

如果您有大量其他不变的属性,您可以使用交集将它们添加到可区分联合中:

type MySelect =
    (
        {
            multi: true;
            onChange: (items: string[]) => void;
        }
        |
        {
            multi: false;
            onChange: (item: string) => void;
        }
    )
    &
    {
        the:        number;
        other:      string;
        properties: string;
    };

答案 1 :(得分:2)

您可以使用通用标识函数执行此操作:

function helper<T extends boolean>(obj: MySelect<T>): MySelect<T> {
    return obj;
}

// MySelect<true> inferred
const mySelect = helper({
    multi: true,
    onChange: (items) => {}
});

Playground Link

也就是说,当您的类型参数没有一组有限的不同选项时,这种技术更有用;在您的情况下,T extends boolean 可能更好地实现为 T.J. Crowder 的回答,没有泛型。