TypeScript is a powerful programming language that extends JavaScript by adding TypeScript-specific features, including static typing. One of the key aspects of TypeScript is its ability to infer types, which can make your code more concise and less error-prone.
In TypeScript, we can declare variables using the let
or const
keywords, similar to JavaScript. The let
keyword allows us to declare mutable variables, whereas the const
keyword is used for declaring constants.
let name: string = "John";
const age: number = 25;
name = "Mike"; // Valid
age = 30; // Error: Cannot assign to 'age' because it is a constant
By explicitly providing a type annotation, we can ensure that variables are assigned values of the correct type. In the above example, we declared name
as a string
and age
as a number
. Trying to assign a value of a different type to these variables will result in a type error.
TypeScript has a powerful type inference system, which infers the types of variables based on their values and how they are used. This helps reduce the need for explicit type annotations and makes our code more expressive.
let myNumber = 42; // TypeScript infers the type as number
let myString = "Hello"; // TypeScript infers the type as string
myNumber = "42"; // Error: Type 'string' is not assignable to type 'number'
myString = true; // Error: Type 'boolean' is not assignable to type 'string'
In the above example, TypeScript automatically infers that myNumber
is of type number
because we assigned it a numeric value. Similarly, myString
is inferred as a string
because we initialized it with a string value. If we try to assign a value of a different type to these variables, TypeScript will throw a type error.
TypeScript can also infer types for function arguments and return types based on how the function is defined and used.
function addNumbers(a: number, b: number) {
return a + b;
}
const result = addNumbers(4, 6); // TypeScript infers the result type as number
result = "10"; // Error: Type 'string' is not assignable to type 'number'
In the above example, TypeScript infers that the function addNumbers
takes two arguments of type number
and returns a value of type number
. When calling the function and assigning the result to the result
variable, TypeScript knows that result
will be of type number
. Trying to assign a different type to result
will result in a type error.
TypeScript's variable declarations and type inference capabilities make it easier to write robust and type-safe code. By providing explicit type annotations, we can ensure that variables are assigned values of the correct type. However, TypeScript's type inference system can save us from specifying types explicitly in many cases, making our code more concise and maintainable.
So whether you prefer explicit type annotations or rely on type inference, TypeScript provides the flexibility to choose the approach that fits your coding style and needs.
noob to master © copyleft