【问题标题】:Better way of extending multiple interfaces扩展多个接口的更好方法
【发布时间】:2021-08-10 20:43:49
【问题描述】:

晚上好,

只是一个快速的,我在打字稿方面不是那么好,但我仍然在寻找解决泛型的方法。 当然有一种更简洁或更简洁的方法来执行以下操作,在这种情况下最佳做法是什么?

export interface Fruit {
  colour: string;
  age: number;
  edible: boolean;
}

export interface A {
  Apple: Fruit[];
  Banana: Fruit[];
  Peach: Fruit[];
  Plum: Fruit[];
  Melon: Fruit[];
}

export interface B {
  diffApple: Fruit[];
  diffBanana: Fruit[];
  diffPeach: Fruit[];
  diffPlum: Fruit[];
  diffMelon: Fruit[];
}

export interface FruitIndex
  extends A, B, (etc)

我有这种情况,但是对于多个接口,它看起来真的很不整洁。 TIA

【问题讨论】:

  • 这个问题不涉及泛型。另外,我不确定你认为什么是“整洁”和“不整洁”,我也不确定你想以“更干净”或“更整洁”的方式做这部分。就像,你可以用this 声明AB 没有那么多冗余,但也许这不是你想要做的?
  • 是的,没有泛型,但我想也许会有一种更简洁的方式来使用泛型。但是,您所链接的正是我正在寻找的。谢谢!更整洁。
  • 好吧,有机会我可以写下来作为答案。

标签: typescript types interface


【解决方案1】:

我希望“整洁”、“整洁”和“干净”在旁观者的眼中。您可以重构 AB 的定义以减少冗余。对于A

export type A = Record<"Apple" | "Banana" | "Peach" | "Plum" | "Melon", Fruit[]>;

这里我们使用the Record&lt;K, T&gt; utility type,一个mapped type,它为联合K中的每个键提供相同的属性值类型T。您可以验证类型是否符合您的预期:

/* type A = {
    Apple: Fruit[];
    Banana: Fruit[];
    Peach: Fruit[];
    Plum: Fruit[];
    Melon: Fruit[];
} */

然后输入B

export type B = { [K in keyof A as `diff${K}`]: A[K] }

这里我们使用key remapping in mapped typestemplate literal types"diff" 添加到A 的所有键中,同时保持值相同。同样,您可以验证类型是否符合您的预期:

/* type B = {
    diffApple: Fruit[];
    diffBanana: Fruit[];
    diffPeach: Fruit[];
    diffPlum: Fruit[];
    diffMelon: Fruit[];
} */

这段代码比你的AB 的原始版本更简洁......但我不知道它是否更“整洁”。对于非专家可以理解的代码,有话要说。看到{ [K in keyof A as `diff${K}`]: A[K] } 的人不知道它的含义可能不会将其描述为“干净”。


对于您的FruitIndex,我看不出有什么方法可以使它更简洁;您需要在某个地方列出您希望扩展的所有父接口。您可以在此处的 extends 一词之后执行此操作,或者您制作一些其他结构将其列出并从中计算 FruitIndex。无论哪种方式,您都会在某处再次输入AB。所以我会保持原样,至少在这个例子中:

export interface FruitIndex extends A, B { }

Playground link to code

【讨论】:

  • 出于兴趣,有没有办法通过K 使用类似于.replace 的方法或正则表达式文字,例如diff 在字符串文字的中间?所以redDiffPlum 并且在新的对象类型中你希望它是“redReturnPlum”仍然具有相同类型的fruit[]?
  • 喜欢this 可能吗?如果这不是您要查找的内容,您可能想要发布一个新帖子(在搜索现有帖子之后),因为评论部分不是使用代码进行详细 Q/A 的最佳位置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多