

Here, the type would be (string | number) which means that the array can hold either string values or number values. In such cases, the compiler treats the type as a union of all types present in the array. This tutorial provides a brief overview of TypeScript, focusing on its type system. The main benefit of TypeScript is that it can highlight unexpected behavior in your code, lowering the chance of bugs.

In such cases, the TypeScript compiler looks for the most common type to infer the type of the object but does not find any super type that can encompass all the types present in the array. This means that your existing working JavaScript code is also TypeScript code. Here, the array has values of type number as well as type string. TypeScript Tutorial for Beginners Programming with Mosh 3.14M subscribers Subscribe 9.9K 477K views 8 months ago Front-end Development TypeScript Tutorial for Beginners.

In this case, it picks the one thats is compatible with all types i.e. TypeScript looks for the most common type to infer the type of the object. In the above example, we have an array that has the values 10, null, 30, and, 40. There may be scenarios where an object may be initialized with multiple types. When we try to assign b to a, the compiler complains saying a number type cannot be assigned to a string type. TypeScript is an Open Source Object Oriented programming language developed and maintained by Microsoft Corporation. The above code shows an error because while inferring types, TypeScript inferred the type of variable a as string and variable b as number. A = b // Compiler Error: Type 'number' is not assignable to type 'string'
