Skip to content

Typescript fail to pick up error with Nullish Coalescing OperatorΒ #62850

@brenhub24

Description

@brenhub24

πŸ”Ž Search Terms

Nullish Coalescing Operator
Type check

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs___

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.0-dev.20251207#code/C4TwDgpgBAKghgcygXigIgIJqgH3QIWzzQGE0AoUSKAZQHsBbCYACwEsA7JVAb3KgFRgiAM4YATuLggA-AC5YiANoBdcgF9K4aPSatOCAKIAbEdF79BwhCICycMAp5KA1lE6KEK+UPEBXCE1NADM-DgBjYDY6DigGBwAKTjA-YCgFXWZ2LlUASnTaRiyDEzNVKD5BKHFmP3FY5NSAOniwBISRIv0uXOQAPgTKqqtRe0coTr1shCbrMUlpKBkZCs0q9VzcgG4NcnJwmJE0xrSMrunylCglSwEeOYkpEAUlTDQAGgIP9DIVdXfbqtyGp9oc6MYIE1jHQEAkAFI0ADyADkmkdxAY2MEQAlWkkOClgJtcnsgA

πŸ’» Code

type Tag = "A" | "B" | "C"
type Something = {
    tagsArray?: Tag[]
}
type SomethingElse = {
    tagsMap: {[k in Tag]?: true}
}
function map(input : Something[]) : SomethingElse[] {
    return input.map((something)=>({
        tagsMap: something.tagsArray ?? {}
    }));
}

const input : Something[]  = [
    {tagsArray: ["A", "B", "C"]},
    {}
]

console.log(JSON.stringify(map(input)))

πŸ™ Actual behavior

Typescript happily passed this line
tagsMap: something.tagsArray ?? {}
This allows potentially assigning an array to type {[k in Tag]?: true}
Looks like the Nullish Coalescing Operator confused typescript?

πŸ™‚ Expected behavior

Typescript should report an error there

Additional information about the issue

Tested in both 5.9.3 and v6.0.0-dev.20251207

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions