Typescript: Unexpected behavior of conditional types on generics

Created on 7 Sep 2019  路  5Comments  路  Source: microsoft/TypeScript

I stumbled upon a rather odd behavior while trying to combine conditional types with generics. It looks like, even when the produced types are structurally different, it's still possible to assign a values between them.

class T1 { t1_tag = 't1' }
class T2 extends T1 { t2_tag = 't2' }

type X<T> = {
  x: T extends T2 ? 'yes' : 'no'
}

let a1: X<T1> = { x: 'no' } // {x: 'yes'} is not valid
let a2: X<T2> = { x: 'yes' } // {x: 'no'} is not valid

// These assignations should not type, but they do
a1 = a2
a2 = a1

At first I thought this might be caused by generics being intentionally ignored but that seemed weird, since the types end up being structurally different and checks seem to work for literals, so I though I would report it, just in case.

TypeScript Version: 3.6.2

Search Terms: generics, conditional type, type inheritance

Expected behavior: exclusive structural conditional types derived from generic should not be assignable to each other.

Actual behavior: assignation seems to pass type check even when types are structurally incompatible.

Playground Link: here

Duplicate

Most helpful comment

The any is independent of the root issue. Check types in conditionals cause type parameters to be incorrectly measured as bivariant.

All 5 comments

I'm on mobile,

Playground

@weswigham

This variation gives errors. This looks similar to things I've seen before. Is this one of those variance markers not being propagated properly?

Duplicate of #31295

Please ignore me failing to use github correctly

Duplicate of #31295

But... there's no any involved here... I don't think...

The any is independent of the root issue. Check types in conditionals cause type parameters to be incorrectly measured as bivariant.

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dlaberge picture dlaberge  路  3Comments

wmaurer picture wmaurer  路  3Comments

remojansen picture remojansen  路  3Comments

manekinekko picture manekinekko  路  3Comments

siddjain picture siddjain  路  3Comments