Microsoft/TypeScript

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

Open

#54,966 建立於 2023年7月11日

在 GitHub 查看
 (7 留言) (2 反應) (0 負責人)TypeScript (6,726 fork)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

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[]

貢獻者指南