TS Simple Types
TypeScript extends JavaScript with static typing for more reliable code. Let’s explore TypeScript’s simple (primitive) types, including string
, number
, boolean
, and more.
Key Topics
Types Overview
In TypeScript, the primitive types include: string
, number
, boolean
, null
, undefined
, and symbol
. The bigint
type is also available for large integers.
String Type
A string
in TypeScript is a sequence of characters. TypeScript ensures that you use string-based operations on string variables.
let firstName: string = "Alice";
// firstName = 123; // Error: Type 'number' is not assignable to type 'string'.
console.log(`Hello, ${firstName}`);
Output
Hello, Alice
Number Type
The number
type covers both integer and floating-point values. TypeScript also supports hex, octal, and binary literals.
let age: number = 30;
age = 31.5;
// age = "thirty"; // Error: Type 'string' is not assignable to type 'number'.
console.log(`Age is ${age}`);
Output
Age is 31.5
Boolean Type
A boolean
type can only be true
or false
. It’s useful for representing binary states.
let isLoggedIn: boolean = false;
function loginUser() {
isLoggedIn = true;
console.log(`User login status: ${isLoggedIn}`);
}
loginUser();
Output
User login status: true
Key Takeaways
- Primitive Types: TypeScript supports standard JavaScript types (string, number, boolean, etc.).
- Static Checking: Assigning the wrong type results in compile-time errors.
- Consistency: Types help maintain consistent and bug-free code.