Exitl0l
Exitl0l

Reputation: 509

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. But! In order for the select option to work it needs to have this key-value pairs to work.

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. 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[]

Upvotes: 0

Views: 2483

Answers (2)

Exitl0l
Exitl0l

Reputation: 509

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.

Nothing fancy. Just a 3 input 1 output component which emits the changes then listens to them in the consuming component.

Upvotes: 0

WisePlatypus
WisePlatypus

Reputation: 118

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

Upvotes: 1

Related Questions