TypeSript - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

Basics

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. Here are some basics of TypeScript:

1. Static Typing:
TypeScript introduces static typing to JavaScript, allowing developers to define types for variables, function parameters, return types, and more. This helps catch errors during development and provides better tooling support, such as code editors offering auto-completion and type-checking.

2. Syntax Similarity to JavaScript:
TypeScript's syntax is largely similar to JavaScript, making it easy for developers familiar with JavaScript to pick up TypeScript quickly.

3. Type Annotations:
TypeScript allows developers to annotate variables, function parameters, and return types with types.
For example:

let num: number = 5;
function add(x: number, y: number): number {
    return x + y;
}

4. Interfaces:
TypeScript provides a way to define custom data types using interfaces. Interfaces define the structure of an object, specifying which properties and methods it should have.
For example:

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

function greet(person: Person) {
    return `Hello, ${person.name}!`;
}

5. Classes:
TypeScript supports object-oriented programming concepts such as classes, inheritance, and access modifiers.
Here's an example of a class in TypeScript:

class Animal {
    name: string;
    
    constructor(name: string) {
        this.name = name;
    }
    
    speak() {
        console.log(`${this.name} makes a noise.`);
    }
}

const dog = new Animal('Dog');
dog.speak(); // Output: Dog makes a noise.

6. Enums:
Enums allow developers to define a set of named constants.
For example:

enum Color {
    Red,
    Green,
    Blue,
}

let c: Color = Color.Green;
console.log(c); // Output: 1

7. Generics:
TypeScript supports generics, allowing developers to write reusable code components that work with a variety of data types.
For example:

function identity<T>(arg: T): T {
    return arg;
}

let output = identity<string>("hello");

These are just some of the basics of TypeScript. TypeScript offers many more features and capabilities for building robust and scalable JavaScript applications.

React with TypeScript

Using TypeScript instead of JavaScript in React offers several benefits:

1. Static Typing:
TypeScript provides static typing, allowing you to define types for variables, props, and state. This helps catch type-related errors during development and improves code robustness.

2. Enhanced IDE Support:
TypeScript enhances developer experience by providing better IDE support. Features like code auto-completion, type checking, and refactoring tools are more effective in TypeScript compared to plain JavaScript.

3. Improved Code Quality:
With static typing, TypeScript helps enforce stricter type rules, leading to better code quality. It reduces the likelihood of runtime errors and makes code easier to understand and maintain.

4. Early Error Detection:
TypeScript performs type checking at compile time, which allows developers to catch errors early in the development process. This reduces the debugging effort and ensures more reliable code.

5. Code Documentation:
TypeScript allows developers to document code more effectively by providing type annotations. This makes it easier for other developers to understand the codebase and its API.

6. Ecosystem Integration:
TypeScript has strong support within the React ecosystem. Many popular libraries and frameworks in the React ecosystem provide TypeScript typings, making it easier to integrate TypeScript into your React projects.

7. Easy Migration:
TypeScript is a superset of JavaScript, which means you can gradually migrate your existing JavaScript codebase to TypeScript. You can start by adding type annotations to existing code and gradually refactor it to take full advantage of TypeScript's features.

Overall, using TypeScript with React can lead to improved developer productivity, code quality, and maintainability of React applications.

Example

Here's an equivalent functional component written in JavaScript and TypeScript:
JavaScript example:

import React from "react";

const Todos = (props) => {
  return (
    <ul>
        {props.items.map((item) => (
            <li key={item}>{item}</li>
        ))}
    </ul>
  );
}

export default Todos;

TypeScript example:

import React from "react";

const Todos: React.FC<{items: string[]}> = (props) => {
  return (
    <ul>
        {props.items.map((item) => (
            <li key={item}>{item}</li>
        ))}
    </ul>
  );
}

export default Todos;

Now, let's explain the differences between the TypeScript version and the JavaScript version:

1. Type Annotations:
In the TypeScript version, we have type annotations specified for the component props using TypeScript syntax. We define that the items prop is an array of strings. In the JavaScript version, there are no type annotations.

2. React.FC Type:
In the TypeScript version, we use React.FC (Function Component) type to define the type of the functional component. Inside angle brackets (< >), we specify the type of props the component is expecting ({items: string[]}). This enforces type checking for the component props. In the JavaScript version, we don't have any such type annotations.

3. Type Inference:
TypeScript provides type inference, which means that even if you don't explicitly specify types, TypeScript can often infer them based on the context. In the JavaScript version, there's no explicit typing, so everything is inferred by JavaScript at runtime.

4. Development Experience:
Using TypeScript provides better development experience due to features like type checking, code auto-completion, and error detection at compile-time. This can lead to fewer runtime errors and easier maintenance of the codebase.

The usage of the Todos component in the App component remains the same whether you're using TypeScript (.tsx) or JavaScript (.jsx). The way you import and use components in your application does not change based on the file extension.

So whether you're using TypeScript (.tsx) or JavaScript (.jsx), your App component would look exactly the same:

import React from 'react';
import Todos from './components/Todos';

function App() {
  return (
    <div>
      <Todos items={['Learn React', 'Learn TypeScript']} />
    </div>
  );
}

export default App;
⚠️ **GitHub.com Fallback** ⚠️