microsoft / microsoft/TypeScript

Allow inline type predicates

Open
#6,474 8 comments 27 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Proposal Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

From #5731

if (<foo is Element>(foo.nodeType === 1)) { 
    // Assume foo is Element here
}

A proposal from @sandersn: https://github.com/Microsoft/TypeScript/issues/5731#issuecomment-162586789

Type Predicate Expressions

A type predicate expression allows you to narrow a union type with a single expression. The syntax is

<variable is type> boolean-expression

When the expression is used in a conditional context, the true branch of the conditional narrows variable to type, while the false branch narrows variable by removing type.

The type predicate expression is of type Boolean, with apparent type of type predicate. The right hand side must be an expression of type Boolean. The left hand side's variable must be a name bound in the current scope. The left hand side's type must be a name bound in the current scope.

Open questions
  1. How does variable capture work? Can a type predicate expression be returned from a function and used to narrow a variable that's no longer in scope? This could be defined to cause an error, but that restriction is neither obvious nor easy to use.
  2. Why reuse the type assertion syntax? The type of the right expression is checked to be Boolean, unlike assertions, and the resulting type is still Boolean, also unlike assertions.

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 by reading the proposal linked from issue #5731 and the Type Predicate Expressions section here. Resolve the listed questions about variable capture, syntax, and Boolean checking before proceeding; done means the inline predicate syntax and its true- and false-branch narrowing behavior are specified and supported for the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.