首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将泛型类型传递给泛型选择器?

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

Stack Overflow用户
提问于 2020-01-30 22:47:59
回答 1查看 195关注 0票数 0

我有一个打字的问题,我不知道如何解决它...

我创建了一个通用状态来管理多个实体。每个实体都有自己的接口,每个接口都是泛型类型的一部分(在我的示例中称为引用)。

我想要的是:当有人需要从这个状态获取实体时,他在select方法(或selectReference ?)中指定所需的接口。和Typescript检查给定接口是否是Reference类型别名的一部分。

我的接口和类型别名:

代码语言:javascript
复制
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

我的选择器:

代码语言:javascript
复制
export const selectReference = () => createSelector(selectRef, adapter.getSelectors().selectAll); // selectRef return an EntityState<Reference>

我的组件:

代码语言:javascript
复制
    export class MyComponent {
    collection$: Observable<Array<A>>;

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

在此示例中,ts linter显示此错误:Type 'Reference' is not assignable to type 'A'。

我该怎么做呢?

提前感谢您:)

EN

回答 1

Stack Overflow用户

发布于 2020-01-30 23:30:32

这本身不是一个答案,但它可能会给你一个想法:

代码语言:javascript
复制
    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

根据我的经验,你总是必须转换它,才能明确地告诉typescript你所期望的类型是什么。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59988588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档