如何让Typescript识别联合中两个相同类型接口之间的通用共性?

如何让Typescript识别联合中两个相同类型接口之间的通用共性?,typescript,generics,Typescript,Generics,我概述了以下几种类型: 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

我概述了以下几种类型:

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';
}
然而,Typescript不喜欢这一点,因为存在类型重叠——但在这种情况下,由于使用了泛型,这是否重要呢?一个或两个实例都可以接受传递的参数

有没有办法让typescript从更大的角度来看待泛型

另一个注意事项是,以下方法可行,但出于显而易见的原因,我宁愿不这样做:

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

我认为您的问题在于您对
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' });
}
接口人{
名称:字符串;
}
接口核心{
fnc:(arg:Person)=>void;//这是更改的行。
args:T;
}
接口一扩展核心{
类型:“modifyPerson”;
}
接口二扩展核心{
类型:“modifyAgeingPerson”;
}
功能修改人员特征(人员:一|二){
person.fnc({…person.args,名称:'Steven'});
}

游戏场。

这并不能解决泛型的问题,函数类型链接到对象类型,args泛型类型与该类型等效,在这种情况下,我需要检查type===modifyAgeingPerson,然后传递func{…person.args,age:12}则此修复无效。在这种情况下,这是否有效:
fnc:(arg:U)=>void
通过此更改,它以不同于对象的方式键入函数,这不会将函数类型链接到arg类型,arg类型是泛型的点
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' });
}