4 comments

  • hankbond4 minutes ago
    As a new TypeScript user these are concepts that have greatly helped me simplify my code and improve reliability discrete of testing. Many LLMs guide in this direction if you loosely ask them, but having a concise post like this with the what and the why is fantastic as reference material. The suggestion to use Separation and a Linter rule is something I'm going to immediately look into for my current project. Great post!
  • robertlagrant55 minutes ago
    This feels right, and I also have never done it (or had the guts to get others to do it).<p>The reason I&#x27;ve not is - say there&#x27;s an optional field. Currently we call that null, probably, and check each time if it&#x27;s there or not. I could instead make a type, like User and UserWithPhoneNumber. Should we be making types for each combination of present&#x2F;absent fields? That can&#x27;t be right.<p>The classic answer is to move the logic inside the domain object, or have a helper function outside the object, so you aren&#x27;t constantly checking for field presence&#x2F;absence, but are instead writing the logic once and calling some code.<p>I&#x27;m not sure in practice types can help with this. But I&#x27;d love to be proven wrong.
    • xx_ns36 minutes ago
      I think this is a slightly different problem. The absence of an optional field, if that&#x27;s a legal state, is meaningful every time you use the type, so you encode it on the field: `phone: ValidPhoneNumber | null`. When it&#x27;s not null you&#x27;re still guaranteed a valid phone number. When it is null, that&#x27;s a legal state you have to handle and which is domain logic, not validation you forgot to do.<p>The combinatorial explosion you&#x27;re picturing only shows up if you make a separate type per combination of present fields, but you don&#x27;t need to. An independent optional field stays one `T | null`. You only reach for distinct types when fields are correlated and present together because they represent a state, and then it&#x27;s a discriminated union on a status field, which is N states, not 2^N.
    • pillmillipedes39 minutes ago
      if a user with&#x2F;without phone number are equally valid states to be then types won&#x27;t help you much. I think it&#x27;s more about writing<p><pre><code> class User{phone: ?PhoneNumber} </code></pre> over<p><pre><code> class User{phone: ?string}.</code></pre>
  • conartist623 minutes ago
    Don&#x27;t forget to freeze the objects
  • ShizuhaLabs40 minutes ago
    [flagged]