TypeScript, a statically typed superset of JavaScript, introduces a robust type system to enhance code quality and developer productivity. Understanding basic types is crucial for leveraging TypeScript's full potential.
In TypeScript, all numbers are floating-point values. There's no distinction between integers and floats.
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
Text data is represented using the string type. You can use single or double quotes for string literals.
let color: string = "blue";
color = 'red';
The boolean type represents true/false values.
let isDone: boolean = false;
Arrays in TypeScript can be written in two ways:
let list: number[] = [1, 2, 3];
let fruits: Array<string> = ['apple', 'banana', 'orange'];
Tuples allow you to express an array with a fixed number of elements whose types are known.
let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error
Enums are a way of giving more friendly names to sets of numeric values.
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type checking during compilation.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
void is the absence of having any type at all. It's commonly used as the return type of functions that do not return a value.
function warnUser(): void {
console.log("This is my warning message");
}
In TypeScript, both null and undefined have their own types named null and undefined respectively.
let u: undefined = undefined;
let n: null = null;
Type assertions are a way to tell the compiler "trust me, I know what I'm doing." It has no runtime impact and is used purely by the compiler.
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// Alternatively
let otherLength: number = (someValue as string).length;
Understanding these basic types forms the foundation for writing type-safe TypeScript code. As you progress, explore more advanced concepts like Generics in TypeScript and Interface Basics to fully harness TypeScript's power.