網站搜尋

如何在 TypeScript 中覆寫型別屬性


例如,我有

type Line = {
  start: Point;
  end: Point;
  color: string; //'cyan'/'aquablue'/...
}

但現在我想在 Line 的基礎上創建新的線類型,以便它可以以數字形式存儲顏色:

type HexColorLine = Point & {
  color: number;
}

現在我期望 HexColorPoint 類型等於

{
  start: Point;
  end: Point;
  color: number;
}

但它等於

{
  start: Point;
  end: Point;
  color: string | number;
}

有沒有一種方法可以覆蓋而不是擴展屬性類型用一些簡短的語法?我真的需要為此完全定義一個新類型嗎?

答案#1

建立一個輔助類型:

type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;

用法:

type HexColorLine = Overwrite<Line, { color: number }>

答案#2

截至 TypeScript 3.5,一個簡單的一次性解決方案可以是:

type HexColorLine = Omit<Line, 'color'> & {
  color: number;
}

答案#3

在 TypeScript 3.5 或更高版本,你可以使用 Omit<Type, Keys>。

對於類型:

type HexColorPoint = Omit<Line, "color"> & {
    color: number;
}

對於介面:

interface HexColorPoint extends Omit<Line, "color"> {
    color: number;
}