如何在TypeScript中覆盖类型属性

问题描述 投票:1回答:3

例如,我有

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

有没有办法覆盖但不用一些简短的语法扩展道具类型?我真的必须为此定义全新的类型吗?

typescript
3个回答
5
投票

创建一个帮助器类型:

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

用法:

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

3
投票

目前不支持此功能。 TypeScript需要一个减法类型的概念。提议存在https://github.com/Microsoft/TypeScript/issues/12215https://github.com/Microsoft/TypeScript/issues/4183

Fix

创建基本类型:

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

2
投票

TL; DR:

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>
type Override<T, U> = Omit<T, keyof U> & U

type ColorNumber =  {
  color: number;
}

type HexColorPoint = Override<
  Line,
  ColorNumber
> // --> {start: Point; end: Point; color: number}

我想你想做

type HexColorLine = Line & {
  color: number;
}

代替

type HexColorLine = Point /* <-- typo? */ & {
  color: number;
}

使用Typescript> 2.8,我可以像这样覆盖:

来自https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

我们没有包含Omit类型,因为它简单地写为Pick <T,Exclude <keyof T,K >>。

// So we define Omit -.-
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>

// Sidenote: 
// keyof is just getting all the keys for a given type separeted by |
// keyof Line --> 'start' | 'end' | 'color'

// And we define Override which unions the type without unwanted keys and the 
// type defining the new keys
type Override<T, U> = Omit<T, keyof U> & U

// just define which properties you want to redefine 
// and remove "Point &" as it will be done in the Override type
type HexColorLine =  {
  color: number;
}
type HexColorPoint = Override<
  Line,
  HexColorLine
> // --> {start: Point; end: Point; color: number}
© www.soinside.com 2019 - 2024. All rights reserved.