Start Coding

Topics

Basic Types in TypeScript

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.

Core Types

Number

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;

String

Text data is represented using the string type. You can use single or double quotes for string literals.

let color: string = "blue";
color = 'red';

Boolean

The boolean type represents true/false values.

let isDone: boolean = false;

Complex Types

Array

Arrays in TypeScript can be written in two ways:

let list: number[] = [1, 2, 3];
let fruits: Array<string> = ['apple', 'banana', 'orange'];

Tuple

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

Enum

Enums are a way of giving more friendly names to sets of numeric values.

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

Special Types

Any

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

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");
}

Null and Undefined

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

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;

Best Practices

  • Use type annotations when TypeScript can't infer the type.
  • Prefer interfaces over type aliases for object types.
  • Use Union Types for variables that can hold multiple types.
  • Leverage Type Inference to reduce unnecessary type annotations.
  • Consider using Strict Mode for enhanced type checking.

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.