例如,我有
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;
}
有没有办法覆盖但是没有使用一些简短的语法扩展道具类型 ?我真的必须为此定义全新的类型吗?
答案 0 :(得分:3)
目前不支持此功能。 TypeScript需要一个减法类型的概念。提案存在https://github.com/Microsoft/TypeScript/issues/12215和https://github.com/Microsoft/TypeScript/issues/4183
创建基本类型:
type LineBase = {
start: Point;
end: Point;
}
type LineBase = LineBase & {
color: string; //'cyan'/'aquablue'/...
}
答案 1 :(得分:1)
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;
}
使用打字稿> 2.8时,我可以像这样覆盖:
来自https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html:
我们没有包含Omit类型,因为它写得很简单 如Pick
>。
// 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}
答案 2 :(得分:1)
创建助手类型:
type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
用法:
type HexColorLine = Override<Line, { color: number }>
答案 3 :(得分:0)
从TypeScript 3.5开始,一个简单的一次性解决方案可能是:
type HexColorLine = Omit<Line, 'color'> & {
color: number;
}
答案 4 :(得分:0)
您可以尝试 Override
包 https://github.com/piotrwitek/utility-types#overwritet-u 中的 utility-types
。
因此,将来您可能想使用其他很酷的助手。