
Ts Simple Types in TypeScript
Simple types, also known as primitive types, are the fundamental building blocks for defining data in TypeScript. These types help enforce type safety and make your code more predictable.
List of Simple Types
string
number
boolean
null
undefined
symbol
bigint
Details and Examples
1. string
Represents textual data.
let firstName: string = "Alice";let greeting: string = `Hello, ${firstName}!`; // Template literals
2. number
Represents numeric values, including integers and floating-point numbers.
let age: number = 30;let height: number = 5.9;
3. boolean
Represents true
or false
.
let isActive: boolean = true;let hasPermission: boolean = false;
4. null
Represents the intentional absence of a value. Often used with union types.
let user: string | null = null;user = "Alice";
5. undefined
Indicates a variable has been declared but not initialized. Also used with union types.
let value: string | undefined = undefined;value = "Initialized";
6. symbol
Represents a unique, immutable value often used as object property keys.
const id: symbol = Symbol("id");const anotherId: symbol = Symbol("id");console.log(id === anotherId); // false
7. bigint
Used for arbitrarily large integers. (Requires ES2020
or later)
let bigNumber: bigint = 1234567890123456789012345678901234567890n;
Type Inference
If you do not explicitly declare a type, TypeScript infers it based on the assigned value.
let name = "Alice"; // Type inferred as stringlet age = 25; // Type inferred as numberlet isStudent = true; // Type inferred as boolean
The any
Type
The any
type is a fallback for variables with unknown types. It disables type checking, making the variable accept any value.
let randomValue: any = "Hello";randomValue = 42; // ValidrandomValue = true; // Valid
Note: Use
any
sparingly as it bypasses TypeScript's type safety.
Type Assertions
You can use type assertions to explicitly tell TypeScript the type of a value.
let value: any = "Hello";let length: number = (value as string).length;
Best Practices for Simple Types
Always Use Explicit Types
This helps in understanding code and preventing unintended behaviors.let score: number = 10; // Better than just 'let score = 10;'
Enable Strict Mode
Enablestrict
orstrictNullChecks
in yourtsconfig.json
to ensure robust type safety.Avoid Using
any
Instead, preferunknown
for safer handling of dynamic types.
Conclusion
Simple types form the foundation of TypeScript's type system. By leveraging these types effectively, you can write safer and more maintainable code. Would you like to explore how to combine simple types with advanced features like unions or type aliases?