简体   繁体   English

如何将泛型类型传递给泛型选择器?

[英]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).每个实体都有自己的接口,每个实体都是泛型类型(在我的示例中称为 Reference)的一部分。

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.我想要的:当有人需要从此状态获取实体时,他在select方法(或selectReference ?)中指定所需的接口,并检查给定的接口是否是Reference类型别名的一部分。

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' .在此示例中, ts linter 显示此错误: 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.根据我的经验,您将始终必须强制转换它以明确告诉打字稿您期望的类型是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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