TypeScript is a statically-typed superset of JavaScript that introduces type annotations and compile-time type checking. One of its main features is type safety, which helps prevent errors by catching issues early during development.
TypeScript includes a range of simple types (or primitive types) that can be used to describe the kind of values you expect to work with in your program.
In this tutorial, we will cover the most commonly used simple types in TypeScript, including examples of how to use them to ensure type safety.
Table of Contents
1. Basic TypeScript Types
In TypeScript, every variable or constant can have a type annotation that describes the type of data it holds. These basic types are fundamental building blocks in TypeScript.
Here are some of the simple types we'll cover:
string
number
boolean
null
undefined
any
unknown
void
never
2. Type Annotations
TypeScript allows you to explicitly declare the type of a variable, function parameter, or return type using type annotations.
Example 1: Basic Type Annotations
let name: string = 'Alice'; let age: number = 25; let isStudent: boolean = true; console.log(name); // Output: Alice console.log(age); // Output: 25 console.log(isStudent); // Output: true
Explanation:
name is explicitly declared as a string.
age is explicitly declared as a number.
isStudent is explicitly declared as a boolean.
3. String Type
The string type is used to represent textual data.
Example 2: Using the string Type
let firstName: string = 'John'; let lastName: string = 'Doe'; let fullName: string = `${firstName} ${lastName}`; console.log(fullName); // Output: John Doe
Explanation:
The string type holds text values. In this example, we concatenate firstName and lastName to form fullName.
4. Number Type
The number type is used to represent both integers and floating-point numbers.
Example 3: Using the number Type
let score: number = 100; let pi: number = 3.14159; let total: number = score + pi; console.log(total); // Output: 103.14159
Explanation:
The number type can represent both integers and decimals.
Arithmetic operations like addition, subtraction, multiplication, and division work just like in JavaScript.
5. Boolean Type
The boolean type can hold true or false.
Example 4: Using the boolean Type
let isAvailable: boolean = true; let isActive: boolean = false; if (isAvailable && !isActive) { console.log('Item is available but not active.'); }
Explanation:
The boolean type is used for values that are either true or false.
Logical operations like && (AND), || (OR), and ! (NOT) can be applied to boolean values.
6. null and undefined Types
In TypeScript, null and undefined are their own types. They represent the absence of a value.
Example 5: Using null and undefined
let emptyValue: null = null; let notAssigned: undefined = undefined; console.log(emptyValue); // Output: null console.log(notAssigned); // Output: undefined
Explanation:
null represents a deliberate absence of a value.
undefined represents an uninitialized value or absence of a value by default.
7. The any Type
The any type allows a variable to hold any type of value. It disables type checking for that variable, making it behave like JavaScript's dynamic typing.
Example 6: Using the any Type
let dynamicVar: any = 'Hello'; dynamicVar = 42; dynamicVar = true; console.log(dynamicVar); // Output: true
Explanation:
The any type lets you assign any value to the variable, even changing its type over time. However, overusing any can reduce type safety.
8. The unknown Type
The unknown type is safer than any because you need to check its type before performing operations on it. It is useful when dealing with values from external sources or unknown inputs.
Example 7: Using the unknown Type
let inputValue: unknown; inputValue = 'A string'; console.log(inputValue); // Output: A string inputValue = 42; if (typeof inputValue === 'number') { console.log(inputValue + 10); // Output: 52 }
Explanation:
The unknown type requires a type check before performing operations. This prevents unsafe operations and enforces more type safety compared to any.
9. The void Type
The void type is used for functions that don't return any value.
Example 8: Using the void Type
function logMessage(message: string): void { console.log(message); } logMessage('This is a message'); // Output: This is a message
Explanation:
The void type indicates that the function does not return a value. This is common for functions that perform side effects like logging or modifying global state.
10. The never Type
The never type represents values that never occur, such as functions that always throw an error or infinite loops.
Example 9: Using the never Type
function throwError(message: string): never { throw new Error(message); } function infiniteLoop(): never { while (true) { // Infinite loop } }
Explanation:
The never type is used for functions that either throw errors or never finish executing (like an infinite loop).
These functions never return a value.
11. Type Inference
In TypeScript, you don’t always need to provide type annotations explicitly. The compiler can infer the type based on the value assigned to the variable.
Example 10: Type Inference in TypeScript
let inferredString = 'Hello, TypeScript!'; // Inferred as string let inferredNumber = 123; // Inferred as number console.log(inferredString); // Output: Hello, TypeScript! console.log(inferredNumber); // Output: 123
Explanation:
TypeScript infers the type of inferredString as string and inferredNumber as number based on the values assigned to them.
12. Union Types
Union types allow a variable to hold multiple types. You can define a union type by separating types with a vertical bar (|).
Example 11: Using Union Types
let id: number | string; id = 123; // Valid id = 'ABC'; // Valid console.log(id); // Output: ABC
Explanation:
The id variable can hold either a number or a string.
This is useful when a value can be of multiple types (e.g., a user ID that could be numeric or alphanumeric).
Conclusion
TypeScript’s simple types provide the foundation for writing type-safe code, ensuring that variables, functions, and objects behave as expected at compile-time.
By explicitly defining types, TypeScript helps catch bugs early, improving the overall robustness of your code.
Key Simple Types Covered:
string: Represents textual data.
number: Represents numeric data (both integers and floating-point numbers).
boolean: Represents true or false.
null and undefined: Represent the absence of a value.
any: Disables type checking and allows any type of value.
unknown: Requires explicit type checking before usage, providing more safety than any.
void: Used for functions that do not return any value.
never: Represents functions that never return or always throw an error.
Union types: Allow multiple possible types for a value.
By understanding and leveraging these basic types, you can write cleaner, more maintainable TypeScript code with fewer runtime errors.