Table of Contents
- Introduction
- What Are Primitive Types in TypeScript?
- Exploring Each Primitive Type
number
string
boolean
null
undefined
symbol
- TypeScript’s Behavior with Primitive Types
- Type Inference and Type Compatibility
- Advanced Use Cases and Examples
- Conclusion
Introduction
In TypeScript, understanding primitive types is fundamental for writing robust and type-safe code. Primitive types are the building blocks of any TypeScript application, representing simple, immutable values. TypeScript provides all the standard primitive types available in JavaScript, with enhanced features such as type checking, type inference, and type safety.
In this article, we’ll explore the six primitive types in TypeScript: number
, string
, boolean
, null
, undefined
, and symbol
. We’ll dive deep into each type’s characteristics, syntax, and use cases, and examine how TypeScript handles them to improve code quality and developer experience.
What Are Primitive Types in TypeScript?
Primitive types are the most basic data types in TypeScript. These types are immutable, meaning their values cannot be changed once they are assigned. When you create a primitive value, it is directly assigned to a variable or constant, and operations are performed on that value, rather than modifying the underlying value itself.
The six primitive types in TypeScript are:
number
: Represents numerical values.string
: Represents sequences of characters (text).boolean
: Represents true or false values.null
: Represents the absence of any object value.undefined
: Represents a variable that has not been assigned a value.symbol
: Represents unique, immutable identifiers often used as object property keys.
Each of these types has its specific behavior and application, which we’ll explore in detail below.
Exploring Each Primitive Type
number
In TypeScript, the number
type is used to represent both integers and floating-point numbers. This is a flexible type, allowing for basic arithmetic and operations. TypeScript, like JavaScript, doesn’t differentiate between integer and floating-point numbers.
Example:
let age: number = 25;
let price: number = 19.99;
let hexValue: number = 0xFF; // Hexadecimal representation
- Special Numeric Values: TypeScript also supports special numeric values such as
NaN
,Infinity
, and-Infinity
.
Example:
let notANumber: number = NaN; // Not a number
let infinity: number = Infinity; // Positive infinity
string
The string
type is used to represent textual data in TypeScript. A string can be created using single quotes ('
), double quotes ("
), or backticks (`
) for template literals.
Example:
let firstName: string = 'John';
let greeting: string = `Hello, ${firstName}!`;
- Template Literals: TypeScript allows the use of template literals, which are strings that can embed expressions directly within the string using
${expression}
.
boolean
The boolean
type represents truthy or falsy values. It can only hold one of two values: true
or false
.
Example:
let isActive: boolean = true;
let isVerified: boolean = false;
The boolean
type is commonly used for conditionals, control flow, and logic operations.
null
The null
type represents the intentional absence of any object value. It’s often used to explicitly indicate that a variable or object is empty or not yet initialized.
Example:
let user: string | null = null;
- Union with Other Types: In TypeScript, you can use
null
with other types by combining them in a union. This allows you to express that a variable may either have a specific type or benull
.
Example:
let userName: string | null = null;
userName = "Alice"; // valid
undefined
The undefined
type represents a variable that has been declared but not yet assigned a value. In JavaScript, undefined
is the default value for uninitialized variables, function parameters, and object properties.
Example:
let height: number | undefined;
height = undefined; // valid
- TypeScript’s Strict Null Checking: When strict null checking is enabled (
strictNullChecks
),undefined
is treated as a distinct type fromnull
, and variables must explicitly be typed asundefined
ornull
if they may have those values.
symbol
The symbol
type is a unique and immutable primitive value that can be used as the key for object properties. Symbols are often used to avoid name collisions in object properties, making them particularly useful in large applications.
Example:
let uniqueKey: symbol = Symbol('uniqueKey');
let obj = {
[uniqueKey]: 'value'
};
- Unique Identity: Each symbol is unique, even if created with the same description.
Example:
let symbol1: symbol = Symbol('test');
let symbol2: symbol = Symbol('test');
console.log(symbol1 === symbol2); // false
TypeScript’s Behavior with Primitive Types
In TypeScript, primitive types are immutable and passed by value. This means that when you assign one primitive value to another variable, TypeScript copies the value, rather than referencing the same memory location. As a result, changes to one variable do not affect others.
Example:
let a: number = 10;
let b: number = a; // b is a copy of a
a = 20;
console.log(b); // 10
In this example, the value of a
is copied into b
. Changing a
does not affect b
because numbers (like other primitives) are passed by value.
Type Inference and Type Compatibility
TypeScript also offers type inference, which allows it to automatically determine the type of a variable based on its assigned value. For example:
let city = 'New York'; // Inferred as string
TypeScript automatically infers that city
is a string
because it is assigned a string literal.
Additionally, TypeScript uses type compatibility rules to check whether two values can be assigned to each other. For instance, a string
can be assigned to a variable of type string
, but a string
cannot be assigned to a number
.
Advanced Use Cases and Examples
While the primitive types in TypeScript are straightforward, they can also be used in more advanced scenarios:
- Type Aliases: You can create type aliases for primitive types to improve code readability and ensure consistency across your application.
Example:
type Age = number;
let userAge: Age = 30;
- Union Types: TypeScript allows you to combine multiple types using union types, including primitive types like
string
andnull
, orundefined
.
Example:
let value: string | null = null;
value = "Hello"; // valid
- Type Assertions: TypeScript allows you to assert a variable to be of a specific type using the
as
keyword.
Example:
let someValue: any = "Hello, World!";
let strLength: number = (someValue as string).length;
Conclusion
Primitive types are the core data types in TypeScript, and understanding how they work is essential for writing type-safe, maintainable code. In this article, we’ve explored each of the six primitive types in detail, from the most commonly used number
, string
, and boolean
, to the more specialized null
, undefined
, and symbol
. We’ve also looked at TypeScript’s handling of these types, how they behave with type inference, and their use in advanced scenarios like type aliases and union types.