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.
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.
did a quick proof-of-concept branch: https://github.com/thomasboyt/immutable-js/commit/82d860587c6a17547c11bdbd10771a0c23ff624a
@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.
Most helpful comment
did a quick proof-of-concept branch: https://github.com/thomasboyt/immutable-js/commit/82d860587c6a17547c11bdbd10771a0c23ff624a