microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.46k stars 12.42k forks source link

Type of pointer to object is treated differently from type of object #59104

Closed nvlang closed 2 months ago

nvlang commented 3 months ago

šŸ”Ž Search Terms

inconsistent inference of type of pointer / alias in generic function

šŸ•— Version & Regression Information

āÆ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.0-dev.20240701#code/KYDwDg9gTgLgBAMwK4DsDGMCWEV1AQwFswAbYAHgDUA+ACgCg4nFUNsUB5KAQSinwCeALkbMxAHzi1aASjgBeanFQATYAkwpgKmaLFNJtSnhAxgKFQGc4lmFE0BzOAH44lANoBdOEOUX1mtoyADT0cgDeenCYCFK8-AIAdJiW8YK0yOhYOFxpAjIRcFFiaDi2cJCaZlAKLFnsuXyCANxF+sxk8ABu+CS+tDACYMAQsZlsOTxN+e4oSIQARsBQnq0A9GtwEADWgsUdwPAOSPhQKgCM-V2+qNsoEADuKHKKcF3R1gNDI2Os2ZxTBIyWbzJYrdabZZQaD7JidODHU4qABMVxuKDuj2eCiU7xSUkGw1GFQgVWWwLmi2WqzgGy2uwEUQAvkx6EygA

šŸ’» Code

export function example<V>(
    functionOrArray:
        | (() => undefined)
        | (V extends string ? V[] : undefined),
) {
    if (Array.isArray(functionOrArray)) { 
        const pointer = functionOrArray; 
        let val: (typeof functionOrArray)[number]; // okay
        let guard1: (v: unknown) => v is (typeof functionOrArray)[number]; // error
        let guard2: (v: unknown) => v is (typeof pointer)[number]; // okay
    }  
}

šŸ™ Actual behavior

(v: unknown) => v is (typeof alias)[number] works, but (v: unknown) => v is (typeof functionOrArray)[number] doesn't.

šŸ™‚ Expected behavior

Expected alias and functionOrArray to either both work or both not work.

Additional information about the issue

No response

MartinJohns commented 3 months ago

Duplicate of #9998.

RyanCavanaugh commented 2 months ago

typeof in that position is going to use the non-control-flowed (i.e. declared, not narrowed) type of the variable, and pointer and functionOrArray have different declared types

typescript-bot commented 2 months ago

This issue has been marked as "Working as Intended" and has seen no recent activity. It has been automatically closed for house-keeping purposes.