首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript使用Observable.of区分联合类型

Typescript使用Observable.of区分联合类型
EN

Stack Overflow用户
提问于 2017-01-04 07:34:57
回答 0查看 1.2K关注 0票数 6

我试图在RxJS中使用TypeScript2.0的区分的联合类型,但是我得到一个错误,我返回的对象不是联合类型的类型之一。

以下是我的类型:

代码语言:javascript
复制
interface Square {
  kind: "square";
  width: number;
}

interface Circle {
  kind: "circle";
  radius: number;
}

interface Center {
  kind: "center";
}

type Shape = Square | Circle | Center;

在这个函数中,我只返回一个没有使用ObservableShape,编译完全正常:

代码语言:javascript
复制
function shapeFactory(width: number): Shape {
  if (width > 5) {
    return {kind: "circle", radius: width};
  } else if (width < 2) {
    return {kind: "square", width: 3};
  }

  return {kind: "center"};
}

当我尝试返回如下所示的Observable<Shape>时:

代码语言:javascript
复制
function shapeFactoryAsync(width: number): Observable<Shape> {
  if (width > 5) {
    return Observable.of({kind: "circle", radius: width});
  } else {
    return Observable.of({kind: "center"});
  }
}

我遇到了编译错误:

代码语言:javascript
复制
Type 'Observable<{ kind: string; radius: number; }>' is not assignable to type 'Observable<Shape>'.
  Type '{ kind: string; radius: number; }' is not assignable to type 'Shape'.
    Type '{ kind: string; radius: number; }' is not assignable to type 'Center'.
      Types of property 'kind' are incompatible.
        Type 'string' is not assignable to type '"center"'.

我希望我的第一个返回值是Observable<{ kind: "circle"; radius: number; }>类型,因为kind是所有Shape类型的区别。奇怪的是,它可以使用Observable.of({kind: "center"}),可能是因为没有其他数据与之关联?

如果我显式地给对象赋值,并为赋值赋予如下类型,我就能够修复它:

代码语言:javascript
复制
let circle: Circle = {kind: "circle", radius: width};
return Observable.of(circle);

虽然这看起来应该是一个不必要的演员阵容。

我这样做是完全错误的,还是为了找出kind应该是值"circle"而不是类型string而进行强制转换是必要的

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41454009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档