Acid Coder
Acid Coder

Reputation: 2747

typescript conditional yield no result when working with generic

const foo =<T extends string>()=>{ 
    type a = T extends string ? true:false // tooltip shows that type a = T extends string ? true : false
    
    const test1:a = true  // Type 'true' is not assignable to type 'a'.(2322)  <===what!!
    const test2:a = false // Type 'false' is not assignable to type 'a'.(2322) <===what!!

    type b = unknown extends unknown ? true:false // tooltip shows that type b = true

    const test3:b = true  // <=== work at expected
    const test4:b = false // Type 'false' is not assignable to type 'true'.(2322) <=== work as expected
}

type b is the expected behaviour, type b is true as expected

however type a is not cannot be determined

what is happening here and how can I solve it

playground

Upvotes: 1

Views: 74

Answers (1)

sam256
sam256

Reputation: 1421

I don't think typescript will resolve your function declaration's generic based on the declaration alone. Instead it is waiting until it sees how the function is actually called before resolving the generic, even though, in your case, you've defined a generic that will always evaluate to true no matter how the function is called.

If you have this code

const foo =<T extends string>()=>{ 
    type a = T extends string ? true:false // tooltip shows that type a = T extends string ? true : false
    
    let test1:a
    return test1

}

foo()

Here the called function foo() shows the correct return type true when you hover over it because when it has a called function TS will evaluate the generic. (There are other problems with the code above, but I believe it illustrates the point.)

Upvotes: 1

Related Questions