Skip to content

T[keyof T] types as constraints #12509

Closed
Closed
@stevekane

Description

@stevekane

TypeScript Version: 2.2.0-dev.20161125

Code

type MapOf<T> { [ x: string ]: T | never } // values only of type T
type Box<T> { value: T }

// Here we show that the above type constrains valid types for values of MapOf<T> to T
const t: MapOf<number> = { foo: 1 } // compiles
const tbad: MapOf<number> = { foo: 'foo' } // does not compile

// assign every value of MapOf<T> to some T
function forMapsOf <T> ( m: MapOf<T>, t: T ) {
  for ( var k in m ) { 
    m[k] = t
  }
} // Compiles and works as expected

// now let's transform the definition of the above function slightly
function forMapsOf <T, M extends MapOf<T>> ( m: M, t: T ) {
  for ( var k in m ) { 
    m[k] = t
  }
} // DOES NOT COMPILE - Says "Type T is not assignable to type M[keyof M]

// The above is crucial for this function below which would take a map of 
// Boxed values and update them from a map of unboxed values
function updateBoxed 
<T, 
 U extends Only<T>, 
 B extends { [ K in keyof U ]: Box<U[K]> }> 
( b: B, u: U ) {
  for ( var k in u ) { 
    b[k].value = u[k]
  }
} // DOES NOT COMPILE - Says "Type U[keyof U] is not assignable to type T"

Expected behavior:
I would expect the value of a type indexing itself to in-fact be all the types of its values. This should be knowable at compile-time and especially so if the type is constrained as T | never

Actual behavior:
Compiler does not recognize that U[keyof U] is the same as T.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions