Home > Article > Web Front-end > 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()
Type System and Array.prototype.includes()
TypeScript enforces type safety, which can lead to errors when using functions like Array.prototype.includes(). This function expects the searchElement argument to have the same type as the array elements. However, in certain scenarios, the input can have a different type, which raises the question of why the type argument is constrained.
The TypeScript library presumes that the searchElement parameter is strictly typed to match the array elements. While this assumption holds true in most cases, it can be problematic when dealing with supertypes. In such cases, the standard TypeScript declaration might need to be overridden to allow supertypes.
Overriding Array.prototype.includes()
One approach is to locally override the standard library declaration through declaration merging. TypeScript lacks supertype constraints, so conditional types are used to emulate them:
<code class="typescript">declare global { interface Array<T> { includes<U extends (T extends U ? unknown : never)>( searchElement: U, fromIndex?: number ): boolean; } }</code>
With this declaration, the original code will work without errors:
<code class="typescript">if (exampleArr.includes(e.key)) {} // okay</code>
Widening Array Type
A simpler solution is to widen the type of exampleArr to readonly string[]:
<code class="typescript">const stringArr: readonly string[] = exampleArr; // no assertion if (stringArr.includes(e.key)) {} // okay</code>
Widening to readonly string[] allows the input to have a different type without compromising type safety. In contrast, widening to string[] is potentially unsafe due to TypeScript's unsound treatment of array covariance.
The above is the detailed content of 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(). For more information, please follow other related articles on the PHP Chinese website!