【问题标题】:$(window).height() is typed to return number | undefined键入 $(window).height() 以返回数字 |不明确的
【发布时间】:2020-10-15 16:17:04
【问题描述】:

我在 typescript (3.9.5) 中有以下内容:

const height: number = $(window).height();

这失败了:

TS2322: Type 'number | undefined' is not assignable to type 'number'.

我正在使用以下相关软件包:

"jquery": "^3.4.1",
"@types/jquery": "^3.5.0"

在打字稿中处理这个问题的正确方法是什么?

【问题讨论】:

  • 我猜它是通用的,没有检查但也许你可以为 $ 添加一个定义...或附加as number

标签: jquery typescript typescript-typings


【解决方案1】:

您不需要指定height 的类型。可以推断。

但是,如果要确保heightnumber 类型的显式,则需要处理$(window).height() 的结果返回undefined 的情况。

例子:

const height: number = $(window).height() || 0

或者,推断类型

// type of height will be number | undefined
const height = $(window).height()

最后一种选择是强制打字系统做你想做的事。这通常不是一个好的做法,但如果您确定结果是一个数字,您可以这样做:

// Not the preferred way, but it's possible.
const height = ($(window).height() as number)

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 2014-10-31
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2011-12-13
    • 2013-03-19
    • 2012-08-19
    相关资源
    最近更新 更多