Basic Types
Primitive types in TypeScript
Introduction
In this lesson, you'll learn about basic types in TypeScript. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with primitive types in typescript.
TypeScript has its own approach to primitive types in typescript, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
// TypeScript primitives
let name: string = "Alice";
let age: number = 30;
let isStudent: boolean = false;
let nothing: null = null;
let notDefined: undefined = undefined;
let bigNumber: bigint = 9007199254740991n;
let uniqueId: symbol = Symbol("id");Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// JavaScript primitives
let name = "Alice";
let age = 30;
let isStudent = false;
let nothing = null;
let notDefined = undefined;
let bigNumber = 9007199254740991n;
let uniqueId = Symbol("id");You may be used to different syntax or behavior.
TypeScript has the same primitives as JavaScript
You may be used to different syntax or behavior.
number type covers both integers and floats
You may be used to different syntax or behavior.
bigint and symbol types exist in TypeScript
Step-by-Step Breakdown
1. String Type
The string type represents text data. Template literals also return strings.
let greeting = "Hello";
let template = `Hi ${name}`;let greeting: string = "Hello";
let template: string = `Hi ${name}`;2. Number Type
Unlike some languages, TypeScript has only one number type for both integers and floating-point numbers.
let int = 42;
let float = 3.14;let int: number = 42;
let float: number = 3.14;3. Boolean Type
Boolean represents true/false values.
let isActive = true;let isActive: boolean = true;4. Type Inference
TypeScript can often infer types from initial values, so explicit annotations aren't always necessary.
let count = 10; // JS: no type infolet count = 10; // TS infers: numberCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- TypeScript has the same primitives as JavaScript
- number type covers both integers and floats
- bigint and symbol types exist in TypeScript
Key Takeaways
- TypeScript has 7 primitive types: string, number, boolean, null, undefined, bigint, symbol
- number handles both integers and decimals
- Type inference reduces the need for explicit annotations