Chapters

  • 0. Introduction

    Free

  • 1. Types & Values

    Free

  • 2. Types are just data

    Free

  • 3. Objects & Records

    Free

  • 4. Arrays & Tuples

    Free

  • 5. Conditional Types
  • 6. Loops with Recursive Types
  • 7. Template Literal Types
  • 8. The Union Type Multiverse
  • 9. Loops with Mapped Types
  • 10. Assignability Quiz
  • 11. Designing Type-Safe APIs
  • 12. Conclusion

Articles

Subscribe

About

Made with ❤️ by @GabrielVergnaud

|Chapters|Articles

TypeScript Assignability Quiz!

When delving into the world of TypeScript, one of the first features you hear about is its structural type system. Unlike other languages, you do not have to provide the exact type a function demands in TypeScript. Another type will do, as long as it's compatible with what's expected.

But what does it mean for a type to be compatible with another one?

Glad you asked! In this chapter, we'll embark on an exploration of TypeScript's concept of assignability. And what better way to sharpen our intuition than playing a game? Just like children disassembling their toys to understand them, we will try to understand TypeScript's most fundamental design choices by testing our assumptions and seeing what breaks. I'll test your intuition of assignability by asking you a series of questions, starting with the one right before you.

Let's find out if you're up to the challenge! 😄

// Is `"Welcome!"` assignable to `string`?

type Quiz = "Welcome!" extends string ? true : false;

// Click on either `true` or `false` to give your answer:
type Test = Expect<Equal<Quiz, 
|
>>;

Assignability is the only language spoken by the type system. Whenever we get a type error, it's always a complaint about an assignability rule that has been broken. These rules may appear straightforward for primitive types, objects or arrays, but what about unions, intersections, read-only & optional properties, or even function types?

Contemplating these questions will take us to the strange land of type variance, a concept that's often misunderstood and – even if you've never heard about it – has likely caused a stumble or two along your path!

Let's play

When it comes to quickly building an intuition, nothing beats a good game. Note that all the forthcoming questions presume that Strict Mode is enabled in our tsconfig.json (as it should be! 😈)

Let's get into it! 🎮

Enroll in Type-Level TypeScript!

Get access to all chapters of the Type-Level TypeScript course and join a community of 1600+ students!

You will find everything you need to become a TypeScript Expert — 12 chapters of in-depth, unique content, and more than 70 fun challenges to practice your new skills.

  • Full access to all 12 chapters

  • 70 type challenges with explanations

  • Lifetime access to all course materials

  • Exclusive discord community

Loading...

⟸ Previous

9. Loops with Mapped Types

Next ⟹

11. Designing Type-Safe APIs