0

I have a problem with Typescript and I don't know how to solve it...

I created a generic state to manage multiple entities. Each entity has it own interface and each of them is a part of a generic type (called Reference in my example).

That I want : when someone need to get an entity from this state, he specifies the desired interface in select method (or selectReference ?) and Typescript check if the given interface is a part of Reference type alias.

My interfaces and type alias:

export interface A { propA: string; onch: string }
export interface B { propB: number; foo: boolean; hehe: string }
export interface C { propC: string; bar: number }
export interface D {}
export type Reference = A | B | C

My selector :

export const selectReference = () => createSelector(selectRef, adapter.getSelectors().selectAll); // selectRef return an EntityState<Reference>

My component :

    export class MyComponent {
    collection$: Observable<Array<A>>;

        getCollection(): void {
            this.collection$ = this.store.pipe( select(fromReferencesSelectors.selectReference());
        }
    }

In this example, ts linter show this error: Type 'Reference' is not assignable to type 'A'.

How can I do this ?

Thank you by advance :)

Adrien SAULNIER
  • 1,651
  • 1
  • 13
  • 19

1 Answers1

0

This is not an answer per se but it might give you an idea:

    export interface A { propA: string; onch: string; }
    export interface B { propB: number; foo: boolean; hehe: string; }
    export interface C { propC: string; bar: number; }
    export type Reference  = A | B | C;

       b: A;
       a: Reference = {
        propA: '', onch: 'string'
      };
        this.b = this.a; // this throws Type 'Reference' is not assignable to type 'A'.
            this.b = this.a as A; // this works

From my experience you will always have to cast it to tell typescript explicitly what is the type that you are expecting.

Ivan Mihaylov
  • 434
  • 2
  • 9