Skip to content

Type inference changed for callbacks with optional parametersΒ #55394

Description

@h-joo

πŸ”Ž Search Terms

optional, inference, callback

πŸ•— Version & Regression Information

  • Behaviour changed between versions 5.0 and 5.1

⏯ Playground Link

https://www.typescriptlang.org/play?jsx=0&module=1&ts=5.1.3#code/KYDwDg9gTgLgBAMwK4DsDGMCWEWMwGxmCgB4AVAPgAowpgATTNAQyIC44qA3Z-JYDmQA0cTCnqgOKJAFsARsQCUcALwU4ciBHzBmKRYLgBvAL4AoM2hwBneM1V5CxKjQjXgAfimyFUZWrgYKH5FAG4LKxRbDQcEAiIoF0h3LzhpeWIRAH1U9N9-dSCQ0KA

πŸ’» Code

export function filter<T>(predicate: (value: T, index: number) => boolean): T {}
const a = filter((pose?: number) => true);

πŸ™ Actual behavior

a gets inferred as number

πŸ™‚ Expected behavior

a gets inferred as number|undefined (this is the case in 5.0.4)

I'm not certain if this change is caused by a bug or intentional, but I couldn't find anything from the announcement at least that made this change, so rather asking for clarification on whether this is an intended behavior

Additional information about the issue

The original definition of filter comes from rxjs (simplified in the example for reporting purpose) : https://github.com/ReactiveX/rxjs/blob/2947583bb33e97f3db9e6d9f6cea70c62a173060/src/internal/operators/filter.ts#L6

Activity

  1. Andarist commented on Aug 16, 2023

    @Andarist
    Contributor

    Changed in 5.1.0-dev.20230317, this is what has been added in this version: diff. So likely the difference comes from #52609 .

    I think this is a bug. Perhaps it was always there in inferFromAnnotatedParameters or maybe there is a specific reason why optional parameters behave differently there. I see that the inference source that is used is just getEffectiveTypeAnnotationNode(declaration) there and that the optional marker is ignored. I'll investigate this later more thoroughly.

  2. fatcerberus commented on Aug 16, 2023

    @fatcerberus

    It’s kind of a gray area, but the current behavior feels more intuitive fwiw - the optional marker suggests the intent is that the callback either receives a number or else nothing at all.

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions