【问题标题】:Looking for a type that is polymorphic in record fields (static duck typing)在记录字段中寻找多态的类型(静态鸭子类型)
【发布时间】:2020-04-18 08:52:31
【问题描述】:

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

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

Playground

这在 TS 中可能吗?

【问题讨论】:

    标签: typescript polymorphism record row-polymorphism


    【解决方案1】:

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

    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; }'
    

    Playground

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 2010-09-22
      • 2011-12-24
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      相关资源
      最近更新 更多