News for hackers. Stuff that matters.
Re:Adding type safety to object IDs in TypeScript by pcthrowaway on Tuesday January 30, 2024 @08:48PM (#39198701)
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...

There are no comments on this comment yet.