我在打字稿(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"
在打字稿中处理此问题的正确方法是什么?
您不需要指定height
的类型。可以推断。
但是,如果要确保height
是number
类型的显式,则需要处理$(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)