类型谓词推断:无人预料的 TS 5.5 特性

  • 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 an if statement, TypeScript can narrow a type. For example, if typeof value === "string", the type of value is narrowed from string | number to string.
  • 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 to isString 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 like ts-reset is still needed for correct inference in such cases.
阅读 18
0 条评论