#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 This approach works inside `createIncrementor()` but anything interacting with the return value will get an error if it tries to access the `counter` property
If I may, why are you explicitly setting a return signature that doesn't match the value being returned? IMO the most straightforward solution is to tweak the signature to match what is being returned
@dotproto I find it useful as a pattern for factories: I’d like to hide the more specific actual type.
@rauschma Ahh, okay. In that case you could tweak your type assertion example to remove the warning about `counter` using an intermediate `as any` assertion
```ts
function createIncrementor2(start = 0): Incrementor {
return {
counter: start,
inc() {
this.counter++;
},
} as any as Incrementor;
}
```
EDIT: That can be further simplified by dropping the type from the function signature, since the return type is being explicitly asserted on the return value
@dotproto Alternative: only `as any` at the end of the `return`.
But there is one significant downside: `this` now has the type `any` (line A): https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgJIgVCBbC4D2UyA3gFDLKgIAUAlAFzIBu+wAJqQL6kwCuGYYPhDJMEOJHRjcBKACZqAZzBwoYZAF5kABgZoMWGWEIlyyLGF5QRZChQT5+kKI2WqwAGjMUqdU3bswAAtgRQA6BydoAGpogG5vQJDw4NCABXwAB2gwAE8AEXwIRQA5fDAAUQAPULBYuOQAekbkagBBWkTOLwpOZDhFfpBchM4gA