Hacker News new | ask | show | jobs
by techsin101 2617 days ago
Tell me few .. to me types were useful for hinting in ide but vscode already gives good hints
1 comments

Types are not just for autocompleting, but also for making illegal states unrepresentable[0].

For example, let's say you have Question model with two types: MultipleChoice and ShortAnswer. In TypeScript you can model it like this:

    type MultipleChoice = {
      mode: 'mc'
      body: string
      choices: string[]
      expectedAnswer: number
    }
    type ShortAnswer = {
      mode: 'sa'
      body: string
      exampleAnswer: string
    }

    type Question = MultipleChoice | ShortAnswer
TypeScript's compiler will then enforce data structure consistency across your entire codebase. For example, if you were rendering a question in React:

    type Props = {
      question: Question
    }
    const MyComponent = (props: Props) => {
      props.question.body // Ok, since all questions have a body
      props.question.choices // Type error, since only MC has choices

      if (props.question.mode === 'mc') {
        props.question.choices // Ok now, since we checked the mode of question
      }
    }
You can also use these types to force certain code to always be correct. For example, if you wanted to display a human-readable version of a Question's mode, you could write:

    const prettyQuestionType: Record<Question["mode"], string> = {
      mc: 'Multiple Choice',
      sa: 'Short Answer',
    }
and now TypeScript will force prettyQuestionType to contain keys for all modes. That includes when you add a new Question mode later.

Once you learn how to lean on the type checker, you think less about such details, and your mind becomes freer to think at a higher level, increasing your overall productivity. There is a learning curve though, so be aware.

[0] https://fsharpforfunandprofit.com/posts/designing-with-types...

this indeed looks useful. so you can give multiple types by using '|' ? and if there is vagueness compiler will let you know.. mind blown.