Understanding type compatibility
In this lesson, we'll learn how TypeScript decides whether an item can be assigned to another, i.e. how TypeScript decides whether types are compatible.
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?
let jones: "Tom" | "Bob" = "Tom";let jane: string = "Jane";jane = jones;
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, ...