Skip to content

Commit

Permalink
Typed toString(). (#261)
Browse files Browse the repository at this point in the history
## Summary

This PR only changes the type value of `toString()` in typeid-js to
allow for the usage of template string types.

## Example

```ts
export type UserTypeString = `user_${string}`;
export type UserTypeID = TypeID<'user'>;

private connectedUsers: Record<UserTypeString, User> = {};

const userId = user.id.toString();
connectedUsers[userId] = user;
```

This code will fail type checking if `user.id.toString()` returns a
string that doesn't start with `user_`. This adds a bit of type safety,
but it also makes the code more readable -- when you look at the
`connectedUsers` Record, you know _exactly_ what it's keyed by, not just
a generic `string`.

Without this change, you instead have to typecast that `toString()`
everywhere:

```
const userId = user.id.toString as UserTypeString;
```

Doable, but ugly.  =)

## How was it tested?

All tests pass, and I've been using a locally-linked version of this in
my project for a while now with no issues.
  • Loading branch information
DanHulton committed Jan 25, 2024
1 parent c723a62 commit 41bf922
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion src/typeid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class TypeID<const T extends string> {
return uuid.toString();
}

public toString(): string {
public toString(): `${T}_${string}` | string {
if (this.prefix === "") {
return this.suffix;
}
Expand Down

0 comments on commit 41bf922

Please sign in to comment.