TypeScript Basic Types: Essential Guide for JavaScript Developers

Making the transition from JavaScript to TypeScript opens up a world of powerful type-checking capabilities. If you’re familiar with JavaScript but new to TypeScript, understanding the basic types is your first step toward writing more reliable and maintainable code.

In this comprehensive guide, we’ll explore TypeScript’s fundamental types and how they help catch errors before your code runs.

Table of Contents

Why TypeScript Types Matter

Before diving into the specific types, let’s understand why they’re important. TypeScript’s type system helps you:

  • Catch errors during development instead of runtime
  • Improve code documentation
  • Enable better IDE support with intelligent code completion
  • Make refactoring safer and easier

Number Type

In TypeScript, all numbers are floating-point values. This includes integers, decimals, and special numeric values.

let decimal: number = 6;
let float: number = 3.14;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
Code language: JavaScript (javascript)

String Type

String values in TypeScript can use single or double quotes, as well as template literals:

let firstName: string = 'John';
let lastName: string = "Doe";
let greeting: string = `Hello, ${firstName} ${lastName}`;
Code language: JavaScript (javascript)

Boolean Type

The boolean type represents true/false values:

let isComplete: boolean = false;
let isValid: boolean = true;
Code language: JavaScript (javascript)

Array Type

TypeScript provides two ways to define array types:

// Using square brackets
let numbers: number[] = [1, 2, 3, 4, 5];

// Using generic array type
let strings: Array<string> = ["hello", "world"];
Code language: JavaScript (javascript)

Object Type

Objects in TypeScript can be typed using interfaces or type aliases:

interface User {
  name: string;
  age: number;
}

let user: User = {
  name: "John",
  age: 30
};
Code language: PHP (php)

Any Type

The any type allows you to work with dynamic values, but use it sparingly as it bypasses TypeScript’s type checking:

let dynamicValue: any = 4;
dynamicValue = "hello";
dynamicValue = true;
Code language: JavaScript (javascript)

Null and Undefined

Null and undefined are subtypes of all other types by default:

let nullValue: null = null;
let undefinedValue: undefined = undefined;
Code language: JavaScript (javascript)

Void Type

Void is typically used as the return type of functions that don’t return a value:

function logMessage(): void {
  console.log("Hello, World!");
}
Code language: JavaScript (javascript)

Type Inference

TypeScript can automatically infer types based on the assigned values:

// TypeScript infers the type as number
let age = 25;

// TypeScript infers the type as string
let message = "Hello";
Code language: JavaScript (javascript)

Union Types

Union types allow a value to be one of several types:

let id: string | number;
id = "abc123";
id = 123;
Code language: JavaScript (javascript)

Best Practices for Using Types

  1. Be Explicit When Necessary

    • Add type annotations when TypeScript’s inference isn’t clear enough
    • Use explicit types for function parameters and return values
  2. Avoid Any When Possible

    • The any type defeats TypeScript’s purpose
    • Use unknown for truly unknown values
  3. Use Strict Mode

    • Enable strict mode in your TypeScript configuration
    • This catches more potential errors
  4. Document Complex Types

    • Use interfaces for complex object shapes
    • Add JSDoc comments for better documentation

Common Type Patterns

Function Types

type Calculator = (x: number, y: number) => number;

const add: Calculator = (a, b) => a + b;
const subtract: Calculator = (a, b) => a - b;
Code language: JavaScript (javascript)

Optional Properties

interface Configuration {
  name: string;
  port?: number;  // Optional property
  debug?: boolean;  // Optional property
}
Code language: PHP (php)

Testing Your Understanding

Try this simple exercise to practice working with TypeScript types:

// Create an interface for a Product
interface Product {
  id: number;
  name: string;
  price: number;
  inStock: boolean;
}

// Implement a function that calculates total price
function calculateTotal(products: Product[]): number {
  return products.reduce((total, product) => total + product.price, 0);
}

// Test your implementation
const products: Product[] = [
  { id: 1, name: "Book", price: 29.99, inStock: true },
  { id: 2, name: "Pen", price: 4.99, inStock: true }
];

console.log(calculateTotal(products)); // Expected: 34.98
Code language: JavaScript (javascript)

Troubleshooting Common Issues

  1. Type ‘string’ is not assignable to type ‘number’

    • This occurs when trying to assign a string to a number variable
    • Convert the string to a number using parseInt() or Number()
  2. Property ‘x’ does not exist on type ‘y’

    • Ensure the property is defined in the interface or type
    • Check for typos in property names

Moving Forward

Now that you understand TypeScript’s basic types, you’re ready to explore more advanced features like generic functions and type guards. These concepts build upon the foundation you’ve learned here.

Remember that TypeScript’s type system is there to help you write better code. Take advantage of its features to create more robust and maintainable applications. As you continue your TypeScript journey, you’ll discover how these basic types combine to form more complex type patterns that solve real-world programming challenges.

Start incorporating these types into your code gradually, and you’ll soon see the benefits of TypeScript’s type system in your development workflow.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap