File: genericCapturingFunctionNarrowing.types

package info (click to toggle)
node-typescript 5.0.4%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 459,140 kB
  • sloc: javascript: 1,972,754; makefile: 6; sh: 1
file content (44 lines) | stat: -rw-r--r-- 1,664 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
=== tests/cases/compiler/genericCapturingFunctionNarrowing.ts ===
function needsToNarrowTheType<First extends { foo: string }, Second extends { bar: string }, SubFirst extends First, SubFirstMore extends First & {other: string}>(thing: First | SubFirst | SubFirstMore | Second) {
>needsToNarrowTheType : <First extends { foo: string; }, Second extends { bar: string; }, SubFirst extends First, SubFirstMore extends First & { other: string; }>(thing: First | SubFirst | SubFirstMore | Second) => void
>foo : string
>bar : string
>other : string
>thing : First | Second | SubFirst | SubFirstMore

    if (hasAFoo(thing)) {
>hasAFoo(thing) : boolean
>hasAFoo : (value: First | Second) => value is First
>thing : First | Second | SubFirst | SubFirstMore

        console.log(thing.foo);
>console.log(thing.foo) : void
>console.log : (...data: any[]) => void
>console : Console
>log : (...data: any[]) => void
>thing.foo : string
>thing : First | SubFirst | SubFirstMore
>foo : string
    }
    else {
        // I would expect this to work because the type should be narrowed in this branch to `Second`
        console.log(thing.bar); // Error: Property 'bar' does not exist on type 'First | Second'.
>console.log(thing.bar) : void
>console.log : (...data: any[]) => void
>console : Console
>log : (...data: any[]) => void
>thing.bar : string
>thing : Second
>bar : string
    }

    function hasAFoo(value: First | Second): value is First {
>hasAFoo : (value: First | Second) => value is First
>value : First | Second

        return "foo" in value;
>"foo" in value : boolean
>"foo" : "foo"
>value : First | Second
    }
}