typescript - 当包裹在 Observable 中时,类型“字符串”不能分配给类型字符串文字
问题描述
鉴于:
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"'.
虽然没有 Observable 是可以的
const obj: Abc = { abcmethod: 'one' };
解决方案
修复是手动转换对象文字
const obj: Observable<Abc> = of({ abcmethod: 'one' } as Abc);