3. Data Types
In TypeScript, understanding basic types and variables is essential as it forms the foundation of the language. TypeScript introduces static typing to JavaScript, enabling developers to define and work with different types of data more efficiently. In this article, we will explore type annotations, declaring variables with explicit types, type inference, and some fundamental data types.
Type Annotations
TypeScript allows developers to specify the type of a variable explicitly using type annotations. This means you can declare what type of data a variable can hold.
let age: number;
let name: string;
let isActive: boolean;
In the code above, we’ve declared three variables with type annotations. age
can only hold numbers, name
can only hold strings, and isActive
can only hold boolean values.
Declaring Variables with Explicit Types
You can also assign values to variables when declaring them, along with specifying their types.
let age: number = 30;
let name: string = "John";
let isActive: boolean = true;
Here, we’ve declared variables age
, name
, and isActive
with their types and assigned initial values.
Type Inference
TypeScript features type inference, which means that the type of a variable can be automatically determined by the compiler based on its value.
let age = 30; // TypeScript infers the type as number
let name = "John"; // TypeScript infers the type as string
let isActive = true; // TypeScript infers the type as boolean
In this case, TypeScript infers the types of the variables age
, name
, and isActive
from their initial values.
Basic Data Types
Number
The number
type represents both integer and floating-point numbers. TypeScript provides support for various numeric formats, such as decimal, hexadecimal, and octal.
let decimal: number = 42.5;
let hex: number = 0x10; // Hexadecimal
let octal: number = 0o20; // Octal
let binary: number = 0b1010; // Binary
String
The string
type is used for text data. You can use single or double quotes to define strings.
let firstName: string = "John";
let lastName: string = 'Doe';
let fullName: string = `John Doe`; // Template literals
Boolean
The boolean
type represents true or false values.
let isLogged: boolean = true;
let isDisabled: boolean = false;
Array
Arrays are collections of values. You can specify the type of elements within the array using square brackets notation.
let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ["apple", "banana", "cherry"];
Any
The any
type allows you to work with values of any type. It’s often used when the type of a variable is not known in advance.
let dynamicValue: any = 42;
dynamicValue = "Hello TypeScript";
Type Assertion
Type Assertion is a powerful feature in TypeScript that allows developers to tell the TypeScript compiler to treat a particular value as a specific type. This feature is useful when you, as a developer, have more information about the type of a value than TypeScript can infer automatically.
When to Use Type Assertion
There are scenarios where TypeScript’s type inference may not fully capture the intended types. For example, when working with dynamic data from external sources or libraries, TypeScript might interpret the type more broadly than what you know it should be. In such cases, type assertion can be used to override TypeScript’s default inference.
Syntax of Type Assertion
Type Assertion in TypeScript uses the angle bracket syntax (<>
) or the as
keyword, followed by the target type.
let variableName = <TargetType>value; // Using angle brackets
let variableName = value as TargetType; // Using the as keyword
Example of Type Assertion
Here’s an example where type assertion is beneficial:
let userInput: any = "Hello, TypeScript!";
let stringLength: number = (<string>userInput).length;
In this example, userInput
is initially declared as any
, which means TypeScript doesn’t have type information about it. However, we know that userInput
should be a string, so we use type assertion to treat it as such. We then access the length
property, which is specific to strings.
Type Assertion vs. Type Casting
Type assertion in TypeScript might look similar to type casting in other languages, but there’s a fundamental difference. Type assertion is a compile-time construct, not a runtime operation. It tells the TypeScript compiler how to understand the code but doesn’t change the underlying JavaScript code generated after compilation.
In contrast, type casting in languages like C++ or Java can change the actual type of an object during runtime. TypeScript, being a superset of JavaScript, doesn’t have the same level of runtime control over types as these languages.
Caution with Type Assertion
While type assertion can be helpful, it should be used with caution. Incorrect type assertions can lead to runtime errors and unexpected behavior. It’s crucial to ensure that the type you assert matches the actual type of the value. TypeScript’s type inference is generally reliable, so type assertion is often necessary only in specific situations.
Conclusion
Understanding basic types and variables in TypeScript is crucial for building reliable and maintainable applications. Type annotations, explicit type declarations, type inference, and fundamental data types are the building blocks that enable developers to work with structured and type-safe code in TypeScript. As you continue to explore TypeScript, you’ll find that these concepts form the basis for more advanced type and data manipulation features the language has to offer.