fosstodon.org is one of the many independent Mastodon servers you can use to participate in the fediverse.
Fosstodon is an invite only Mastodon instance that is open to those who are interested in technology; particularly free & open source software. If you wish to join, contact us for an invite.

Administered by:

Server stats:

10K
active users

– 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).
exploringjs.com/tackling-ts/ch

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.

exploringjs.comTyping objects • Tackling TypeScript

@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