Type Inference in TypeScript: Understanding Best Common Types

In this video, you will learn how the best common types are inferred by TypeScript Type Inference.

Code

type Person = { age: number };
type Teacher = Person & { classes: string[] };
type Student = Person & { grade: number };
function getMembersOfSchool(): Person[] {
let s1: Student = { age: 12, grade: 6 };
let s2: Student = { age: 14, grade: 7 };
let t1: Teacher = { age: 30, classes: ["A", "B"] };
let t2: Teacher = { age: 31, classes: ["C", "D"] };
return [s1, s2]
}

You can also edit this code in TypeScript Playground

Full Transcript

Hello friends,

It's harit from bonsaiilabs. Today, I will show you how TypeScript infers the best common types during its inference calculation.

To start, I will create a type called Person which contains one member called age of type number. Next, I will create a new type called Teacher which combines the existing Person type and a adds another member called classes of type string[]. This field will tell us which classes a teacher is teaching.

I will create one more type called Student which also intersects the existing Person type with another member called grade of type number. This will represent the grade a student has received.

I will now create a function called getMembersOfSchool(). With-in this function, I will first create 2 students with different ages and grades. I will then create 2 teachers with different ages and the classes they teach.

Now comes the interesting part. I first return both students in an array. Since we have not explicitly defined the return type of the function, TypeScript will infer the return type. In this case, since both students are returned, TypeScript infers the return type as Student[]. Now, if I change the return values to contain both teachers, TypeScript infers the return type of function as Teacher[]. However, if I mix the return value to contain a student, and a teacher, the TypeScript inference infers its type as an array of the union of Student and Teacher type.

Now, both Teacher and Student are also valid Person since they contain member age inside them, however, TypeScript does not infer the return type of Person since none of the return instances are of type Person strictly. In case your requirement is to have them as Person, you can add an explicit return type of Person in the function declaration signature, which becomes the return type of function and since both instances returned are also Person, the code compiles successfully.

Great! I hope you now have the understanding on how best common types are inferred in TypeScript. Thank you for your time and I will see you again in another video.