我喜欢这样做,只是使用正确的类型。
const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null;
const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>;
[当将鼠标悬停在querySelectorAll
上时,我会很喜欢。 return 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。那你可以做。
但是同样,这里不需要。