microsoft / microsoft/TypeScript

Allow type narrowing for arrays using Array#forEach and assertion function

Open
#52,389 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

lib Update Request

Configuration Check

My compilation target is ES5 and my lib is the default.

Missing / Incorrect Definition

Array type narrowing using Array#forEach with assertion function, in a fashion similar to Array#every, has not been defined. Also applies to ReadonlyArray.

Sample Code

const foo: (number | string)[] = ['aaa'];

function assertString(x: unknown): asserts x is string {
  if (typeof x !== 'string') throw new Error('Must be a string!');
}

foo.forEach(assertString);
foo[0].slice(0); // foo should be string[] from here

Documentation Link

Based on Array#every<S extends T> from lib.es5.d.ts.


A pull request for implementing this definition has been created #52388.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib/lib.es5.d.ts, using the existing Array#every definition as the reference. Check the Array and ReadonlyArray forEach declarations against the provided assertion-function example. Done means the example narrows the array element type after forEach without errors and both mutable and readonly arrays are covered.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.