Immutable-js: Use `this` type in TypeScript

Created on 3 Mar 2016  路  4Comments  路  Source: immutable-js/immutable-js

Since TypeScript 1.7 there is a special type called this which can be used to simplify work with extended records:

class Store extends Record({}) {

}

let store = new Store({});

// store is `Store` here

let newStore = store.withMutations(store => {
    // store is `Map` here!
    // so we can't access store instance methods anymore :-(
})

// newStore is `Map` here! not desired behavior

All we need to do to fix this issue is use this type:

withMutations(mutator: (mutable: this) => any): this;

It can be done in all the signatures that return a copy of an object.

Most helpful comment

All 4 comments

Is anyone working on this? Seems like it would fix the huge pain of working with records in TypeScript. With this change, this now correctly typechecks:

import * as I from 'immutable';

const StateRec = I.Record({
  a: 1,
  b: 'foo'
});

// We can define a class for this record extending I.Record.Class to specify
// the properties:
class State extends StateRec {
  a: number;
  b: string;
}

// state is an instance of the State class
const state = new State();
const stateP = state.set('a', 2);

// This fails to typecheck currently, because `stateP` is `Map<string, any>`
// However, if we simply change the declaration of Map.set to be:
//     set(key: K, value: V): this;
// it works just fine :)

console.log(stateP.a); 

Unless I'm missing something this is basically just a find-replace job on various methods that return updated versions of the same structure (set, setIn, update, remove, merge...).

I'd like to be able to add some sort of TypeScript test cases to the repo to make it easier to work on this going forward, but I can't find a good way to add type samples to the repo that can actually import dist/immutable.js and dist/immutable.d.js. For now I'm just using a separate folder with the module npm link-ed in so I can do import * as I from 'immutable' as usual.

@thomasboyt Any update as to the status of this?

This landed in master branch yesterday. A new release is coming soon which will include this change.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sljuka picture sljuka  路  3Comments

migueloller picture migueloller  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

NullDivision picture NullDivision  路  4Comments

jbonta picture jbonta  路  3Comments