RxJs/Typescript 抛出“类型 {} 上不存在属性 clientX" [英] RxJs / Typescript throws 'property clientX does not exist on type {}'

查看:134
本文介绍了RxJs/Typescript 抛出“类型 {} 上不存在属性 clientX"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些非常简单的事情,只需在鼠标悬停时记录 event.clientX,这是模块代码:

I am trying to do something very simple, just log the event.clientX on mouseover, and this is the module code:

import { Observable, Subject } from 'rxjs';
import StarSky from './starsky';
import constants from '../constants/index';

const HERO_Y = constants.HERO_Y(StarSky.canvas);

export const StarShip = Observable.fromEvent(StarSky.canvas,'mousemove')
  .map((event)=> {
    return {
      x: event.clientX,
      y: HERO_Y
    }
  })
  .startWith({
    x: StarSky.canvas.width /2,
    y: HERO_Y
  })

那我晚点订阅,喜欢:

StarShip.subscribe(x =>  console.log(x));

发生的事情是打字稿编译器不断抛出这种特殊类型的错误:

What is happening is that typescript compiler keeps throwing an error of this particular kind:

Property clientX does not exist on type {}

我猜是因为它仍然是一个空的 Rx Subject,并且 clientX 还没有存在,因为它需要通过鼠标悬停进行初始化.这有点愚蠢,因为如果我删除 .clientX,并将 event 留在那里作为 x,它会毫无问题地注销.

I am guessing because its still an empty Rx Subject, and clientX is not yet still there as it needs to be initialised via mouseover. This is kind of silly because if I remove .clientX, and leave event there as x, it logs out with no problems.

如何解决这种不兼容性并解决此错误?

How to combat this incompatibility and work around this error?

不好意思,刚发现解决方法是放类型声明

I am sorry, just found out that the solution is to put type declaration

(event: MouseEvent) => { ... }

就这样.

推荐答案

'类型 {} 上不存在属性 clientX'

'property clientX does not exist on type {}'

这是因为 observable 没有输入:

This is because the observable is not typed:

Observable.fromEvent(StarSky.canvas,'mousemove')

您可以添加注释作为通用参数:

You can add an annotation as a generic param:

Observable.fromEvent<MouseEvent>(StarSky.canvas,'mousemove')

或者像你所做的那样回调.

Or the callback as you have done.

这篇关于RxJs/Typescript 抛出“类型 {} 上不存在属性 clientX"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆