Typescript 在记录字段中查找多态类型(静态duck类型)

Typescript 在记录字段中查找多态类型(静态duck类型),typescript,polymorphism,record,row-polymorphism,Typescript,Polymorphism,Record,Row Polymorphism,我正在寻找一种在记录字段中具有多态性的类型,这样它就可以接受包含更多字段的记录,并限制所有涉及的记录在这些额外字段中重合: type foo = { first: string, last: string }; const o = { first: "Foo", last: "Oof", age: 30 }; const p = { first: "Bar", last: "Rab", age: 45 }; const q = { first: "Baz", last: "Zab", gend

我正在寻找一种在记录字段中具有多态性的类型,这样它就可以接受包含更多字段的记录,并限制所有涉及的记录在这些额外字段中重合:

type foo = { first: string, last: string };

const o = { first: "Foo", last: "Oof", age: 30 };
const p = { first: "Bar", last: "Rab", age: 45 };
const q = { first: "Baz", last: "Zab", gender: "m" };

const main = (o: foo) => (p: foo) => o.first + o.last

// goal

main(o)(p); // type checks
main(o)(q); // type error


这在TS中可能吗?

您可以通过添加泛型参数来实现

const main = <T extends foo>(o: T) => (p: T) => o.first + o.last

main(o)(p); // allowed
main(o)(q); // Property 'age' is missing in type '{ first: string; last: string; gender: string; }'
const main=(o:T)=>(p:T)=>o.first+o.last
主要(o)(p);//允许
主要(o)(q);//类型{first:string;last:string;gender:string;}中缺少属性“age”

这是因为泛型类型是从第一个参数(
o
)推断出来的,并解析为

{first:string,last:string,age:number}

现在,第二个参数(
p
)类型应该可以分配给上述参数