[英]Typescript convert a type described by an Interface to another?
I know that types exists for a reason. 我知道类型存在是有原因的。
But my collegues'd like to hide the leaky abstraction i have in one of my component. 但我的同事们想要隐藏我在其中一个组件中的漏洞抽象。 I am using a big config interface to hold all the information my main component needs to work and one of the properties is an array or listable elements that'll form a multiselect.
我使用一个大的配置接口来保存我的主要组件需要工作的所有信息,其中一个属性是一个数组或可列表元素,它们将构成一个多选。 Basically my array has a type like this:
基本上我的数组有这样的类型:
export interface Column {
label: string;
property: string;
}
But we are using a 3rd party multiselect component , which accepts only it's own typed array as options. 但是我们使用的是第三方多选组件 ,它只接受它自己的类型数组作为选项。 Like:
喜欢:
export interface IMultiSelectOption {
id: any;
name: string;
disabled?: boolean;
isLabel?: boolean;
parentId?: any;
params?: any;
classes?: string;
image?: string;
}
In our case id -> property
, and name -> label
. 在我们的例子中,
id -> property
和name -> label
。 But! 但! In order for the select option to work it needs to have this key-value pairs to work.
为了使select选项起作用,它需要使这个键值对起作用。
How can I convert our own type to the type of the expected multiselect to work? 如何将我们自己的类型转换为预期的多选项类型? I can't just make another list as type
IMultiselectOption
b/c that wouldn't solve the leaky abstraction issue. 我不能只将另一个列表作为类型
IMultiselectOption
b / c来解决漏洞抽象问题。 I cannot convert it in my recieving component where all the magic happens (basically this is the curtain that hides all the magic) b/c type Column[]
props doesn't exists on type IMultiselectOption[]
我不能在我的接收组件中转换它所有的魔法发生(基本上这是隐藏所有魔法的窗帘)b / c类型
Column[]
道具不存在类型IMultiselectOption[]
In my case I also had to use several type for the same data, but represented/organised diferently for frontend and backend uses. 在我的情况下,我还必须使用几种类型的相同数据,但代表/组织不同的前端和后端使用。
I just have a Helper Service conversion where I convert my Object like so: 我只是有一个帮助服务转换,我转换我的对象,如下所示:
ColumnToIMultiSelectOption(column: Column): IMultiSelectOption {
return <IMultiSelectOption>{
id: column.property,
name: column.label,
}
}
The issue is solved by embedding the 3rd party component into another helper component. 通过将第三方组件嵌入到另一个帮助程序组件中来解决该问题。 This way I was able to manipulate the data and tweak it as multiselect component needs it.
通过这种方式,我可以操作数据并在多选组件需要时对其进行调整。 Thanks to @Eliseo this idea was the winner.
感谢@Eliseo这个想法是赢家。
Nothing fancy. 没有什么花哨。 Just a 3 input 1 output component which emits the changes then listens to them in the consuming component.
只有3输入1输出组件发出更改然后在消费组件中监听它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.