我有一个打字的问题,我不知道如何解决它...
我创建了一个通用状态来管理多个实体。每个实体都有自己的接口,每个接口都是泛型类型的一部分(在我的示例中称为引用)。
我想要的是:当有人需要从这个状态获取实体时,他在select方法(或selectReference ?)中指定所需的接口。和Typescript检查给定接口是否是Reference类型别名的一部分。
我的接口和类型别名:
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我的选择器:
export const selectReference = () => createSelector(selectRef, adapter.getSelectors().selectAll); // selectRef return an EntityState<Reference>我的组件:
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'。
我该怎么做呢?
提前感谢您:)
发布于 2020-01-30 23:30:32
这本身不是一个答案,但它可能会给你一个想法:
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你所期望的类型是什么。
https://stackoverflow.com/questions/59988588
复制相似问题