如何在TypeScript中重写类型属性
例如,我有如何在TypeScript中重写类型属性,typescript,Typescript,例如,我有 type Line = { start: Point; end: Point; color: string; //'cyan'/'aquablue'/... } 但现在我想在线条的基础上创建新的线条类型,以便将颜色存储为数字: type HexColorLine = Point & { color: number; } 现在我希望HexColorPoint类型等于 { start: Point; end: Point; color: numbe
type Line = {
start: Point;
end: Point;
color: string; //'cyan'/'aquablue'/...
}
但现在我想在线条的基础上创建新的线条类型,以便将颜色存储为数字:
type HexColorLine = Point & {
color: number;
}
现在我希望HexColorPoint类型等于
{
start: Point;
end: Point;
color: number;
}
但它等于
{
start: Point;
end: Point;
color: string | number;
}
是否有一种方法可以覆盖,但不能使用一些简短的语法扩展prop类型?我真的必须为此定义全新的类型吗 目前不支持这一点。TypeScript需要一个减法类型的概念。建议存在,并且 修理 创建基类型:
type LineBase = {
start: Point;
end: Point;
}
type LineBase = LineBase & {
color: string; //'cyan'/'aquablue'/...
}
TL;医生:
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 = Point /* <-- typo? */ & {
color: number;
}
type HexColorLine=Point/*2.8我可以这样重写:
发件人:
我们没有包括省略类型,因为它的编写非常简单
作为选择
//所以我们定义了省略--
类型省略=拾取
//旁注:
//keyof只是将给定类型的所有键通过|
//行的键-->“开始”|“结束”|“颜色”
//我们定义了覆盖,它将类型与不需要的键和
//键入定义新键的命令
类型覆盖=省略(&U)
//只需定义要重新定义的属性
//并删除“点&”,就像在覆盖类型中一样
类型六角色线={
颜色:数字;
}
类型HexColorPoint=覆盖<
行,,
六色线
>//-->{开始:点;结束:点;颜色:编号}
创建助手类型:
type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
type Overwrite=Pick&U;
用法:
type HexColorLine = Overwrite<Line, { color: number }>
type HexColorLine=覆盖
从TypeScript 3.5开始,一个简单的一次性解决方案可以是:
type HexColorLine = Omit<Line, 'color'> & {
color: number;
}
type HexColorLine=省略&{
颜色:数字;
}
您可以从实用程序类型
包中尝试覆盖
。
因此,在将来,您可能会希望使用其他很酷的助手。我很确定您不能像尝试那样覆盖。您可以在不使用color属性的情况下声明SimpleLine
,然后将Line
和HexColorLine
声明为扩展SimpleLine
?我想知道你为什么不能这样做吗?谢谢,这很有帮助!我有一个类型,我需要缩小属性上的类型,这可以工作。这对TypeScript v3.9仍然有效吗?
type HexColorLine = Overwrite<Line, { color: number }>
type HexColorLine = Omit<Line, 'color'> & {
color: number;
}