- TypeScript 5.5 Update: It will be released in the next few months. A specific PR by Dan Vanderkam has been merged, enabling inference of type predicates from function bodies using control flow analysis.
- Narrowing with
if
Statements: In anif
statement, TypeScript can narrow a type. For example, iftypeof value === "string"
, the type ofvalue
is narrowed fromstring | number
tostring
. - Function for Type Checking: A function like
isString
can be used to check if a value is a certain type. But without a return type annotation, TypeScript may not infer the narrowing. - Return Type Annotation: Adding a return type annotation like
value is string
toisString
function restores the narrowing. However, keeping this annotation in sync with the function implementation can be a pain. - Dan's PR in Action: With TypeScript 5.5, the function
isString
can infer the type predicate from the function body. This simplifies type narrowing and makes the type system more powerful. - Complex Type Narrowing: Functions like
isObjAndHasIdProperty
can now perform complex type narrowing without explicitly writing the type predicate. - Filter and Inference:
filter(Boolean)
does not automatically infer the correct type. Using a library likets-reset
is still needed for correct inference in such cases.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。