Hacker News new | ask | show | jobs
by shadowgovt 1711 days ago

  interface ServerResponse {
    data: unknown;
  }
... this is the most common way I see unknown used. Then when you fetch data from the server, you are reminded by the compiler that you should do some duck-type checking on it to make sure it's shaped correctly (since responses from a server can be any shape; is it a 200 with your data, or did a caching layer vend you an old version of this data structure, or is something catastrophically wrong and you're seeing a 200 where the payload is HTML saying "Set up your apache server," etc.)

BTW, TypeScript has another useful tool for tying the runtime typing and static typing together: type guards.

  function isUserRecord(x: unknown): x is UserRecord {
    return (x as UserRecord).name !== undefined;
  }
This is a boolean function but the type system understands that in codepaths where it returns true, the 'x' argument is known to have the UserRecord type. Great for codifying your type-discernment logic.