microsoft / microsoft/TypeScript

*explicit* type guard passed to Array.filter does not narrow type

Open
#54,966 7 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Control Flow Help Wanted Possible Improvement
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

array.filter, type guard, explicit, is

🕗 Version & Regression Information

TS 3.9.7–5.1.6, target version ES2019 or later (releases earlier than 3.9.7 didn’t have Object.fromEntries)

⏯ Playground Link

Playground link with relevant code

💻 Code
interface Element { type: Elem['type'], children: Node_[] }
interface CodeBlock extends Element { type: 'cb', children: string[] }
interface Field extends Element { type: 'f', name: string }
interface FieldList extends Element { type: 'fl', children: Field[] }

type Elem = CodeBlock | Field | FieldList
type Node_ = Elem | string

function getMeta2(fieldLists: Elem) {
	return Object.fromEntries(
		fieldLists.children
			.filter((n: Node_): n is FieldList => typeof n !== 'string' && n.type === 'fl')
			.flatMap((fl) => fl.children)
			.map((f) => [f.name, f.children[0]?.toString()]),
	)
}
🙁 Actual behavior
> .flatMap((fl) => fl.children)
Property 'children' does not exist on type 'Node_'.
  Property 'children' does not exist on type 'string'.
🙂 Expected behavior

The return type of filter should be FieldList[]

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 with the linked Playground and the reduced Array.filter example in the issue, then trace how the explicit type-guard callback is checked and how filter's result type is inferred. Confirm the fix by checking that the filtered value is treated as FieldList[] and that the subsequent flatMap access is accepted.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.