如何为querySelector(All)绑定正确声明返回类型

问题描述 投票:0回答:1

我喜欢这样做,只是使用正确的类型。

const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null;
const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>;

[当将鼠标悬停在querySelectorAll上时,我会很喜欢。 return NodeListOf<...> (+2 overloads)的类型现在我知道那些重载是什么或意味着<...>不能正常工作,所以我尝试了...

但是这样我得到qsaNodeListOf<any> has no callable signatures的错误

typescript bind declare
1个回答
0
投票

您完全不需要键入它。 TypeScript会很高兴地推断出类型:

const qs = document.querySelector.bind(document);
const qsa = document.querySelectorAll.bind(document);

您正在执行的操作的问题是,您给出的是函数提供的结果的类型,而不是函数的类型。


如果要定义一个新函数,但由于某种原因TypeScript无法推断类型,则在类型(非值)上下文中,可以使用typeof来获取某种类型。例如:

type QSFunction = typeof document.querySelector;

const qs = document.querySelector.bind(document) as typeof document.querySelector;

由于type赋值的右侧或as是类型上下文,所以typeof存在TypeScript的typeof,而不是JavaScript。那你可以做。

但是同样,这里不需要。

© www.soinside.com 2019 - 2024. All rights reserved.