#TypeScript – surprisingly tricky to fix:
type Incrementor = {
inc(): void,
};
function createIncrementor(start = 0): Incrementor {
return {
counter: start, // error
inc() {
this.counter++; // error
},
};
}
Best solution (AFAICT): Assign object to variable, return variable (then excess properties are allowed).
https://exploringjs.com/tackling-ts/ch_typing-objects.html#allowing-excess-properties-example-incrementor
EDIT: Key point: It’s tricky to return a subtype of Incrementor (because of excess props). The code is just a toy example, with flaws.
@rauschma What about this ?
interface Incrementor {
readonly counter: number;
inc(): void
}
function createIncrementor2(i = 0): Incrementor {
return {
get counter() {return i},
inc() {
i++;
},
}
}
@pygy I’d like to hide implementation details, so I’d do: https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgJIgVCBbC4D2UyA3gFDLKgIAUAlAFzIBu+wAJqQL6kwCuGYYPhDJMEOJHRjcBKACZqCXlCzhkAXmQAGBmgxYZYQiXLIsYZSLIUKVOiZs2lKvGADUbgNymKnADSm3NxAA
(Looking at the code right now, I realize that I should change the interface because with only .inc():void there is no way to retrieve the current counter. But that doesn’t change the basic challenge.)
@rauschma I might have initially missed the point...
The chalenge is to use the factory pattern with pseudo-private fields through type shenanigans ?
@rauschma Why not use the closure scope for private fields as you'd do in plain JS ?
...
Replying to myself : I guess it can make figuring things out with the debugger more ergonomic. Do you have other reasons ?
@pygy I want to illustrate the point I made in the other post—via a toy example.
@rauschma Sorry for the noise, I'm reading my TL from the top (defaut behavior on mamot.fr), I've yet to scroll that deep...
@pygy I wouldn’t say shenanigans: We need a factory for objects of a given type. But it returns an object that is a subtype. Due to how TS handles excess properties of literals (*not* objects coming from variables), we get errors.
@rauschma Oh, I see.