我喜欢这样做,只是使用正确的类型。
const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null;
const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>;
当在 codium 中徘徊在querySelectorAll
上时,我会喜欢很多。 返回NodeListOf<...> (+2 overloads)
类型 我现在知道这些重载是什么或意味着什么<......>不起作用,所以我尝试...
但是这样我得到错误qsa
说NodeListOf<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。然后你可以做。
但同样,这里不需要。