【问题标题】:How to get Typescript to recognise generic commonalities between two of the same type of interface in a union?如何让 Typescript 识别联合中两个相同类型的接口之间的通用共性?
【发布时间】:2020-09-20 12:36:30
【问题描述】:

我列出了几种类型:

interface Person {
    name: string;
}
interface Core<T> {
    fnc: (arg: T) => void;
    args: T;
}
interface One extends Core<Person> {
    type: 'modifyPerson';
}
interface Two extends Core<Person & { age: number }> {
    type: 'modifyAgeingPerson';
}

然后我有一个函数可以处理修改一个人或一个老年人的共享属性 - 因为它有一个联合类型,一个例子如下:

modifyPersonCharacteristics(person: One | Two) {
    person.fnc({ ...person.args, name: 'Steven' });
}

Typescript 不喜欢这样,因为存在类型重叠 - 但在这种情况下,因为使用了泛型,这是否重要? One 或 Two 的实例都可以接受传递的参数。

有没有办法让 typescript 看到泛型的大局?

附带说明一下,以下是可行的,但出于显而易见的原因,我宁愿不这样做:

modifyPersonCharacteristics(person: One | Two) {
    if (person.type === 'modifyPerson') {
        person.fnc({ ...person.args, name: 'Steven' });
    } else {
        person.fnc({ ...person.args, name: 'Steven' });
    }
}

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    我认为您的问题是您将fnc 的参数定义得太窄。关于大局的观点——关键是你的fnc 将适用于任何扩展(或相交)Person 的类型,所以它只需要这样声明,就像这样

    interface Person {
        name: string;
    }
    interface Core<T> {
        fnc: (arg: Person) => void;  //This is the line that's changed.
        args: T;
    }
    interface One extends Core<Person> {
        type: 'modifyPerson';
    }
    interface Two extends Core<Person & { age: number }> {
        type: 'modifyAgeingPerson';
    }
    
    function modifyPersonCharacteristics(person: One | Two) {
        person.fnc({ ...person.args, name: 'Steven' });
    }
    

    游乐场here.

    【讨论】:

    • 这并不能解决泛型的问题,函数类型链接到对象类型,而 args 泛型类型等同于该类型,在我需要检查的情况下键入 === modifyAgeingPerson 然后传递 func { ...person.args, age: 12 } 那么此修复将不起作用。
    • 在这种情况下,这是否可行:fnc: &lt;U extends Person&gt;(arg: U) =&gt; void;
    • 通过此更改,它以与对象不同的方式键入函数,这不会将函数类型链接到作为泛型点的 arg 类型
    猜你喜欢
    • 2022-10-15
    • 2018-12-12
    • 2021-10-30
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2022-11-05
    • 2018-11-24
    相关资源
    最近更新 更多