给出:
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' };
答案 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') });