繁体   English   中英

如何使 TypeScript 中的可选通用

[英]How to make optional generic in TypeScript

我创建了一个 function 来选择一个元素

function select(selector: string, parent: Document | Element | HTMLElement = document): Element | HTMLElement | null {
  return parent.querySelector(selector)
}

上面的 function 工作得很好,但后来我意识到会有一些用例,仅指定上述函数返回HTMLElement是不够的。 有时元素的类型可能是HTMLInputElement等。所以为了应对这种情况,我将我的函数设为通用

function select<T>(selector: string, parent: Document | Element | HTMLElement = document): Element | HTMLElement | T | null {
  return parent.querySelector(selector)
}

但通过这样做,我失去了该元素的可能方法。 为了更好地理解,请看以下示例:

select('.container')

通过使用上面的代码,我没有自动完成可用方法。 现在是下一个示例,我将自动完成可用方法。

select<HTMLDivElement>('.container')

到目前为止我所尝试的是; 在 SO 本身上,我找到了一个答案,其中声明T = void然后泛型将变为可选,但我仍然没有自动完成。

PS - 为这篇文章建议一个更好的标题。

您可以使用extends来指定泛型的基本类型

function select<T extends Element = Element>(selector: string, parent: Document | Element | HTMLElement = document): T | null {
  return parent.querySelector(selector)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM