简体   繁体   中英

How to pass generic type into a generic selector?

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM