Skip to content

T[keyof T] types as constraints #12509

Closed
Closed

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.

Activity

  1. mhegazy commented on Nov 26, 2016

    @mhegazy
    Contributor

    I am not not sure i understand the issue. so bear with me..
    I do not see how the maps is related tot he boxed version. Mapof<T> forgets all the properties by vertue of the indexer. so it does not fit with the updateBoxed function. i would expect this to be typed as:

    type Boxed<T> = {
        [P in keyof T]: { value: T[P] }
    }
    function updateBoxed<U> (b: Boxed<U>, u: U) {
        for (var k in u) {
            b[k].value = u[k]
        }
    }
    
    // usage
    
    var obj = { a: 1, b: "string" };
    
    var boxed = boxify(obj);
    
    updateBoxed(boxed, { a: 2 });// OK
    updateBoxed(boxed, { a: 2, b: "anotherString" });// OK
    updateBoxed(boxed, { a: false });// Error
  2. ahejlsberg commented on Nov 28, 2016

    @ahejlsberg
    Member

    Steven (@stevekane) Check out #12528 for an example of how to implement this.

  3. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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