包裹在Observable中的类型'string'不可分配给type字符串文字

时间:2018-10-30 15:39:41

标签: typescript rxjs

给出:

interface Abc {
  abcmethod: 'one' | 'two';
}

此行将导致错误

const obj: Observable<Abc> = of({ abcmethod: 'one' });

其中

import { of } from 'rxjs';

错误是:

TS2322: 
Type 'Observable<{ abcmethod: string; }>' is not assignable to type 'Observable<Abc>'.   
Type '{ abcmethod: string; }' is not assignable to type 'Abc'.     
Types of property 'abcmethod' are incompatible.       
Type 'string' is not assignable to type '"one" | "two"'.

在没有可观察的情况下就可以了

const obj: Abc = { abcmethod: 'one' };

2 个答案:

答案 0 :(得分:1)

修正是手动转换对象文字

const obj: Observable<Abc> = of({ abcmethod: 'one' } as Abc);

答案 1 :(得分:0)

您必须将属性值的类型范围设置为'one' | 'two',否则TypeScript假定该值具有string类型,该类型与您的类型不兼容。正确的解决方案是:

const obj: Observable<Abc> = of({ abcmethod: (<'one' | 'two'> 'one') });
相关问题