5. Basic Types in TypeScript
Page 5 | Listen in audio
```html
TypeScript is a powerful tool that extends JavaScript by adding static types. This feature allows developers to catch errors early in the development process, improving code quality and maintainability. One of the foundational concepts in TypeScript is understanding its basic types. These types form the building blocks for more complex data structures and are essential for leveraging TypeScript's full potential.
Let's delve into the basic types in TypeScript, exploring their syntax, usage, and how they compare to JavaScript's dynamic typing.
Boolean
The boolean
type in TypeScript is a simple true/false value, similar to JavaScript. Boolean values are useful for control flow and condition checks. Here’s how you declare a boolean type in TypeScript:
let isComplete: boolean = false;
With static typing, TypeScript will alert you if you try to assign a non-boolean value to this variable, providing early error detection.
Number
In TypeScript, the number
type is used to represent both integer and floating-point numbers. TypeScript, like JavaScript, does not differentiate between integer and floating-point numbers, so all numbers are of type number
. Here is an example:
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
TypeScript supports various numeric literals, such as decimal, hexadecimal, binary, and octal, making it versatile for different use cases.
String
The string
type is used for textual data. In TypeScript, strings can be enclosed in single quotes, double quotes, or backticks for template strings. Template strings are especially useful for embedding expressions and multi-line strings:
let color: string = "blue";
let fullName: string = `John Doe`;
let age: number = 30;
let sentence: string = `Hello, my name is ${fullName}. I'll be ${age + 1} years old next month.`;
Template strings enhance readability and reduce errors in string concatenation.
Array
Arrays in TypeScript can be defined in two ways. The first method uses the type followed by square brackets, and the second method uses the generic Array
type:
let list: number[] = [1, 2, 3];
let list: Array = [1, 2, 3];
Both notations are equivalent, allowing flexibility in how you declare arrays. TypeScript enforces type consistency within arrays, preventing accidental mixing of types.
Tuple
Tuples allow you to express an array with a fixed number of elements whose types are known. This can be particularly useful when you want to represent a pair of values with different types:
let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error
Tuples provide a way to define a structured collection of elements, improving code clarity and type safety.
Enum
Enums are a way of giving more friendly names to sets of numeric values. By default, enums begin numbering their members starting at 0. However, you can change this by manually setting the value for one of its members:
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
Enums enhance code readability and help prevent errors associated with using hard-coded numeric values.
Unknown
The unknown
type is a top type that can hold any value. It’s similar to any
but is safer because it requires the developer to perform some type checking before performing operations:
let notSure: unknown = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Using unknown
encourages developers to perform runtime checks, ensuring type safety.
Any
The any
type is a powerful way to opt out of type checking. It allows any type to be assigned to a variable:
let looselyTyped: any = 4;
looselyTyped.ifItExists(); // okay, ifItExists might exist at runtime
looselyTyped.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
While any
provides flexibility, it should be used sparingly as it bypasses the benefits of static typing.
Void
The void
type is used to indicate the absence of a type, commonly used as the return type of functions that do not return a value:
function warnUser(): void {
console.log("This is my warning message");
}
Void helps clarify the intention of functions, making code easier to understand and maintain.
Null and Undefined
In TypeScript, both null
and undefined
have their types. By default, null
and undefined
are subtypes of all other types, which means you can assign them to any type:
let u: undefined = undefined;
let n: null = null;
However, when using the --strictNullChecks
flag, null and undefined are only assignable to themselves and any
.
Never
The never
type represents the type of values that never occur. Functions that never return or always throw an exception have this type:
function error(message: string): never {
throw new Error(message);
}
This type is useful for exhaustive type checking, ensuring all possible cases in a function are handled.
Understanding these basic types is crucial for effectively using TypeScript. They provide the foundation for more advanced features, such as interfaces and classes, and enable developers to write robust, error-free code. By leveraging TypeScript's static typing, developers can catch errors early, enhance code readability, and improve overall software quality.
```Now answer the exercise about the content:
What is the primary benefit of using static types in TypeScript as mentioned in the text?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: