#Why does typescript seem "unhelpful" when it comes to `toString()`?

1 messages · Page 1 of 1 (latest)

mental geyserBOT
#
bawdyinkslinger#0

Preview:```ts
type ToString = {toString: () => string}
type Foo = {bar: string}

function a(): Foo & ToString {
return {bar: "a", toString: () => "a"}
}

function b(): Foo & ToString {
return {bar: "b"}
}

function c(): Foo {
return {bar: "c", toString: () => "c"}
...```

astral canopy
#

!ts

mental geyserBOT
#
type ToString = { toString: () => string };
type Foo = { bar: string };

function a(): Foo & ToString {
  return { bar: "a", toString: () => "a" };
}

function b(): Foo & ToString {
  return { bar: "b" };
}

function c(): Foo {
  return { bar: "c", toString: () => "c" };
//                   ^^^^^^^^
// Object literal may only specify known properties, and 'toString' does not exist in type 'Foo'.
}
astral canopy
#

I'm not understanding how this helps me:

a is fine. That makes sense to me.
b is okay-ish. Since I'm explicitly stating the return should have a toString, I wish it enforced I implement it, but I understand that every object comes with a default implementation.
c on the other hand just seems annoying: b established that typescript understands object literals have a default toString. Why do I have to explicitly put it on a type if it's not going to enforce I implement it anyway?

Can someone explain why this works this way? It seems unhelpful.

raven thistle
#

Seems like a reasonable default, if you want to override toString you need to do so explicitly

wintry lichen
#

so there's specifically extra typechecking for excess properties, and only excess properties

astral canopy
wintry lichen
#

not that anyone is supposed to rely on that

#

but also, that doesn't mean that people don't rely on it

astral canopy
astral canopy
analog hearth
#

In theory, maybe TS could special-case toString, as it's something that can still be "used" even if it's not explicitly included in the type.

#

In practice, it's probably not common enough to be worthwhile?

#

If people are overriding toString it's way more common to do that with a class, and not include it on object literals

astral canopy
#

Why though? It sounds like I'm not writing idiomatic code

analog hearth
#

I think that style of adding toString implementations is more common in OOP-heavy style coding, which is probably why I associate it more with classes than raw JS objects.

astral canopy
#

Okay thanks, @analog hearth and everyone