Skip to content

Comment on Adding type safety to object IDs in TypeScriptparent

Comments

What is the problem with the workaround suggested in the last comment there?

Define a type guard using a "type predicate"[1].

For example:

    type UserId = `user_${string}`;
    type GroupId = `group_${string}`;

    const addUserId = (id: UserId) => {
      // do something
    }

    const processId = (id: string) => {
      if (id.startsWith('user_') {
        // type error here:
        addUserId(id);
      } else if (otherCondition)
        // do other things
      }
    }
Instead you define a function:
    const isUserId = (some: string): some is UserId => some.startsWith('user_');
Now you can use it as follows:
    const processId = (id: string) => {
      if (isUserId(id)) {
        // no more error:
        addUserId(id);
      } else if (otherCondition)
        // do other things
      }
    }
[1]: https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...

You shouldn't need to write this kind of thing manually for every such type.

    function is<T extends string>(value: string, prefix: T): value is `${typeof prefix}_${string}` {
      return value.startsWith(`${prefix}_`)
    }

You can now do `is(id, 'user')`.

If you do that often you probably want to create separate functions, e.g.:

    function isFactory<T extends string>(prefix: T) {
      return (value: string) => is(value, prefix)
    }

    const isUser = isFactory('user')
    const isOrder = isFactory('order')
Not too bad.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.