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...