📝
Programming10 dk okuma10 Ocak 2024

Writing Safer Code with TypeScript

Learn the fundamentals of TypeScript and discover how to write safer code. Detailed guide about type system, interfaces, and React integration.

TR

TheRedGeek

Teknoloji Yazarı

#TypeScript#JavaScript#Programming#React

Writing Safer Code with TypeScript

TypeScript is the type-safe version of JavaScript. In this article, we will learn the fundamentals of TypeScript and how we can write safer code.

What is TypeScript?

TypeScript is an open-source programming language developed by Microsoft. It adds a type system to JavaScript and allows you to write safer code.

Basic Types

Primitive Types

let name: string = "TheRedGeek"
let age: number = 25
let isActive: boolean = true
let skills: string[] = ["JavaScript", "TypeScript", "React"]

Object Types

interface User {
  id: number
  name: string
  email: string
  isAdmin?: boolean // Optional property
}

const user: User = { id: 1, name: "John Doe", email: "john@example.com" }

Generic Types

Generics prevent code duplication while ensuring type safety:

function createArray(length: number, value: T): T[] {
  return Array(length).fill(value)
}

const stringArray = createArray(3, "hello") const numberArray = createArray(3, 42)

Union Types

Variables that accept multiple types:

type Status = "loading" | "success" | "error"

function handleStatus(status: Status) { switch (status) { case "loading": return "Loading..." case "success": return "Success!" case "error": return "Error occurred!" } }

Interface vs Type

Interface

interface Animal {
  name: string
  makeSound(): void
}

interface Dog extends Animal { breed: string }

Type

type Animal = {
  name: string
  makeSound(): void
}

type Dog = Animal & { breed: string }

Utility Types

TypeScript's built-in utility types:

interface User {
  id: number
  name: string
  email: string
  password: string
}

// Partial - makes all properties optional type PartialUser = Partial

// Pick - selects only specific properties type UserCredentials = Pick

// Omit - removes specific properties type PublicUser = Omit

React with TypeScript

Component Props

interface ButtonProps {
  text: string
  onClick: () => void
  variant?: "primary" | "secondary"
  disabled?: boolean
}

const Button: React.FC = ({ text, onClick, variant = "primary", disabled = false }) => { return ( ) }

Best Practices

1. Strict Mode: Enable strict mode in TypeScript config 2. Explicit Types: Use explicit type definitions whenever possible 3. Interface First: Define interfaces first, then implement 4. Use Generics: Use generics to prevent code duplication

Conclusion

TypeScript improves code quality and prevents errors in large projects. With the fundamentals we learned in this article, you can write safer and more maintainable code.

Bu Yazıyı Paylaş

Daha Fazla İçerik İçin Abone Olun

En yeni teknoloji yazılarımızdan haberdar olmak için bültenimize abone olun.