首页  >  文章  >  web前端  >  以下是一些标题选项,全部采用问题格式: 关注类型安全: * 为什么 TypeScript 限制 Array.prototype.includes() 类型参数? * 如何使用 Array.prototype.includes()

以下是一些标题选项,全部采用问题格式: 关注类型安全: * 为什么 TypeScript 限制 Array.prototype.includes() 类型参数? * 如何使用 Array.prototype.includes()

Barbara Streisand
Barbara Streisand原创
2024-10-26 22:04:03826浏览

Here are a few title options, all in the question format:

Focus on Type Safety:

* Why Does TypeScript Restrict Array.prototype.includes() Type Arguments? 
* How Can I Use Array.prototype.includes() With Supertypes in TypeScript?
* TypeScript Type Safety

类型系统和 Array.prototype.includes()

TypeScript 强制执行类型安全,这可能会在使用 Array 等函数时导致错误。原型.includes()。此函数期望 searchElement 参数与数组元素具有相同的类型。但是,在某些情况下,输入可以具有不同的类型,这就提出了为什么类型参数受到约束的问题。

TypeScript 库假定 searchElement 参数的类型严格匹配数组元素。虽然这个假设在大多数情况下都是正确的,但在处理超类型时可能会出现问题。在这种情况下,可能需要重写标准 TypeScript 声明以允许超类型。

重写 Array.prototype.includes()

一种方法是本地重写通过声明合并来声明标准库。 TypeScript 缺乏超类型约束,因此使用条件类型来模拟它们:

<code class="typescript">declare global {
  interface Array<T> {
    includes<U extends (T extends U ? unknown : never)>(
      searchElement: U,
      fromIndex?: number
    ): boolean;
  }
}</code>

使用此声明,原始代码将不会出现错误:

<code class="typescript">if (exampleArr.includes(e.key)) {} // okay</code>

加宽数组类型

更简单的解决方案是将 exampleArr 的类型扩展为 readonly string[]:

<code class="typescript">const stringArr: readonly string[] = exampleArr; // no assertion

if (stringArr.includes(e.key)) {} // okay</code>

扩展为 readonly string[] 允许输入具有不同的类型而不影响类型安全。相比之下,由于 TypeScript 对数组协方差的处理不健全,扩大到 string[] 可能是不安全的。

以上是以下是一些标题选项,全部采用问题格式: 关注类型安全: * 为什么 TypeScript 限制 Array.prototype.includes() 类型参数? * 如何使用 Array.prototype.includes()的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn