如何将字符串数组const映射到并集类型

时间:2019-08-25 03:18:47

标签: typescript

我有一个字符串数组,我想从中定义一个新类型,其中属性实际上是数组中的元素。数组的类型不同,我有一个根据输入数组返回不同类型的函数。


const RGBColor = ["R" , "G" ,  "B"] as const
const YRBColor = ["Y" , "R" ,  "B"] as const

function Map<TInputColor extends readonly string[]>(x: TInputColor): TOutputColor<TInputColor>;

如果输入为RGBColor,则输出类型为

{
   R: number;
   G: number;
   B: number;
}

如果输入为YRBColor,则输出类型为

{
   Y: number;
   R: number;
   B: number;
}

那么,我应该如何定义TOutputColor?

TOutputColor<TInputColor>
{
   ???????
}

1 个答案:

答案 0 :(得分:0)

使用映射类型:

public ObservableCollection<Point> points { get; set; } = new ObservableCollection<Point>();

internal void ExcelFileOpen(object sender, System.EventArgs e)
{
    // Do not re-initialise the collection anymore.
    //points = new ObservableCollection<Point> { new Point { } };
    points.Add(new Point { name = "point1", code = 1 });
    points.Add(new Point { name = "point2", code = 2 });
    points.Add(new Point { name = "point3", code = 3 });
}