【问题标题】:Typescript extend two interfaces like type?打字稿扩展了两个像类型一样的接口?
【发布时间】:2021-04-30 11:54:06
【问题描述】:

在查看the documentation 和这个SO Question 之后,我正在寻找的行为如下:

type A = {
  a:string
};
type B = {
  b:string
};

type C = A & B & {
   c:string
};

我的问题是:可以在一行中使用接口完成相同的行为吗?

【问题讨论】:

  • 我隐约记得在这个问题上看到过重复,但我找不到。
  • 请考虑提供minimal reproducible example 您正在尝试做的事情,并有足够的结构来区分好答案和坏答案。现在它有点了:你有空对象类型,所以Primary1Primary2 彼此等价,Secondary 只等价于{prop: string}。您可以扩展多个接口,例如 interface Secondary extends Primary1, Primary2 { prop: string },但我不确定这是否真的满足您在示例中没有更多内容的任何用例。
  • 我猜了一下,希望这就是你要找的
  • 谢谢,我更新了。

标签: typescript


【解决方案1】:

你可以extend a comma-separated list of interfaces at once,只要接口没有不同类型的重叠属性:

interface Primary1 { prim1: string };
interface Primary2 { prim2: string };
interface Secondary extends Primary1, Primary2 { prop: string }

declare const secondary: Secondary;
secondary.prim1.toUpperCase(); // ok
secondary.prim2.toUpperCase(); // ok
secondary.prop.toUpperCase(); // ok

Playground link to code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2020-12-25
    • 2021-09-20
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多