Home > database >  How to use unique array for some type elements?
How to use unique array for some type elements?

Time:11-10

I try to make a navigation step where to store current element. Element could be User {id: string, name: string}, Group {id: string, name: string, blocked: boolean}, Expirience {id: string, years: number}.

So, navigation could be as:

public navigation: User[] | Group[] | Expirience[]
add(entity: User[] | Group[] | Expirience[]) {}
remove(entity: User[] | Group[] | Expirience[]) {}

Problem is it is not scalable, tomorrow it could be another type as Car{id: number, name: string}. How to unify this?

Important: all of type should contains id and name to display in navigation

CodePudding user response:

Here you have scalable solution:

type Base = {
  id: string;
  name: string;
}

type User = {
  tag: 'User'
} & Base

type Group = {
  tag: 'Group'
} & Base

type Expirience = {
  tag: 'Expirience'
} & Base

type Allowed = User | Group | Expirience

type MakeArray<T extends Base> = T extends Base ? T[] : T

type Result = MakeArray<Allowed>

class Foo<T extends Base> {
  add(entity: MakeArray<T>) {
  }
  remove(entity: MakeArray<T>) { }
}

Playground

You can store all your allowed types/interfaces in Allowed.

MakeArray converts a union of elements to union of arrays of elements. In other words, applies [] to every element in the union. See docs

Base contains all required properties.

If tomorrow you will decide to add Car interface, just add it to Allowed

  • Related