microsoft / microsoft/TypeScript
Allow inline type predicates
Nobody has claimed this yet.
- 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
<variableistype>boolean-expressionWhen 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
- 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.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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