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



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

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

当在 codium 中徘徊在querySelectorAll上时,我会喜欢很多。 返回NodeListOf<...> (+2 overloads)类型 我现在知道这些重载是什么或意味着什么<......>不起作用,所以我尝试...

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

你根本不需要输入它。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。然后你可以做。

但同样,这里不需要。

最新更新