给定:
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);
您必须将属性值的类型边界设置为'one' | 'two'
,否则TypeScript会假定该值具有string
类型,这与您的类型不兼容。正确的解决方案是:
const obj: Observable<Abc> = of({ abcmethod: (<'one' | 'two'> 'one') });