DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

Basic TypeScript for JavaScript Programmers

1. Basic Type Annotation

 let helloWorld: string = "Hello World"; function (nums: Array<number>): Promise<number>{ } 
Enter fullscreen mode Exit fullscreen mode

2. Interfaces

  • Declaring and using interfaces.
  • Extending interfaces.
  • Declaration merging.

3. Types

  • Declaring types.
  • Using intersections.
  • Function types.

4. When to Use type vs interface

type User = { name: string; age: number; }; type Admin = User & { role: string; }; interface User { name: string; age: number; } interface Admin extends User { role: string; } interface User { name: string; } interface User { age: number; } // Resulting type: { name: string; age: number } 
Enter fullscreen mode Exit fullscreen mode

🧠 When to Use What?
Use interface when:

  • You're working with object-oriented code.
  • You want to take advantage of declaration merging.
  • You're defining public APIs or libraries.
    Use type when:

  • You need to define union, tuple, or primitive types.

  • You want to create complex compositions using intersections.


5. Type Inference

TypeScript can automatically infer types based on the assigned value:

let message = "Hello"; // inferred as string let count = 42; // inferred as number 
Enter fullscreen mode Exit fullscreen mode

You can mention that explicit typing is optional when the context provides enough information.


6. Union and Literal Types

type Status = "success" | "error" | "loading"; function showStatus(status: Status) { console.log(status); } 
Enter fullscreen mode Exit fullscreen mode

Useful for modeling finite states.


7. Optional and Readonly Properties

interface User { name: string; age?: number; // optional readonly id: number; // cannot be changed } 
Enter fullscreen mode Exit fullscreen mode

8. Enums

enum Role { Admin, User, Guest } const userRole: Role = Role.Admin; 
Enter fullscreen mode Exit fullscreen mode

Great for defining named constants.


9. Generics

function identity<T>(arg: T): T { return arg; } const output = identity<string>("Hello"); 
Enter fullscreen mode Exit fullscreen mode

Generics allow you to write reusable and type-safe code.


10. Type Assertions

let someValue: unknown = "this is a string"; let strLength = (someValue as string).length; 
Enter fullscreen mode Exit fullscreen mode

Useful when you know more about the type than TypeScript does.

Reference:-

  1. https://www.typescriptlang.org/docs/handbook

Top comments (0)