Skip to content

Conditionnal return type not recognized inside the functionΒ #59618

Closed as not planned
@Tristan-WorkGH

Description

@Tristan-WorkGH

πŸ”Ž Search Terms

"not assignable",
"parametized argument",
"conditional return"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about 5.1.6

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.1.6#code/JYOwLgpgTgZghgYwgAgJIBMLmDYcBGANigN7LDoBcyAzmFKAOYDcyIcAthAPzV0MgWyAL4BYAFASYAVxAIwwAPYhkHAJ4y5AHgAqGMMggAPSCHQ00mbLgLFkAHzbTChAHwAKUDEU1qe9GAAlH76hiZY5pZYCjZEKNy09EzI1CDOhMgkEsg55DDIniDeFgC8JU4ugZnZubVQEGDSUCppLsw1tTkA9F0AolBQfmoADigA5K2EY+QWIIoGcDQ0wIzscchgihsj4-4GxqaRGNE4eOsJ-Mmp6WMAdO4ATADMDw+BHSKGhDSkH3UNTRUXh8two7XEnVyPX6g2QOh2yDGl0E02As3myEWy1WthQm22o0RezChwsx2sZzsFySghSFSm92er3eENyYnE7IkxAMYA4w2Q5XUmgQ7kmgXBPRKrmQ3I2fOuLi5DTlwweAtUGlkIpI7C41DGYwANOQqIixsJxRJJdLZbzVXwaYwJEA

πŸ’» Code

interface Identifiable { id: string; name?: string; }

function myfunc<TIdt extends Identifiable | null>(infos: TIdt): TIdt extends Identifiable ? string : null {
    if (infos == null) {
        return null;
        //Err: Type 'null' is not assignable to type 'TIdt extends Identifiable ? string : null'.(2322)
    } else {
        return infos.id;
        //Err: Type 'string' is not assignable to type 'TIdt extends Identifiable ? string : null'.(2322)
    }
}

let tmp = myfunc(null);
//=> let tmp: null
let tmp2 = myfunc({name: '', id: ''});
//=> let tmp2: string

πŸ™ Actual behavior

tsc doesn't seem to match the if statement with the conditional return.

On the other hand it understand what I want to say when calling the method.

πŸ™‚ Expected behavior

What I expect is for typescript to understand in the if that if the argument is null then I can only return null, and alse only return a string, like defined in the function signature.

Additional information about the issue

I have the impression that the signature is correct as typescript infer correctly when calling the function, so the problem is inside the function with the if?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions