Understanding type compatibility
Explore how TypeScript's structural typing enables compatibility between variables, objects, and functions. Understand assignment rules and how subset and superset types interact to help you write more robust React applications.
We'll cover the following...
We'll cover the following...
Basic type compatibility #
Consider the code below. Hopefully, it is no surprise that TypeScript isn’t happy with the assignment on the last line because the types aren’t compatible.
let firstName: string = "Fred";
let age: number = 30;
firstName = age; // Type 'number' is not assignable to type 'string'.
What about the code below. Will TypeScript be happy with the assignment on the last line?
What if we switch the assignment around:
jones = jane;
Will TypeScript be happy with the assignment on the last time now?
So, if a type is a subset of another type, it can be assigned to it. However, if a type is a superset of another type, it ...