devmeetings-react-ts-fork
  • Devmeeting React + Typescript
  • Speed dating
  • Typescript
    • It's just JavaScript
    • Basic types
    • Typing objects
    • Typing functions
    • Modules
    • Generics
    • Tasks
  • Hello React
    • Quick look around
    • The first component
    • JSX
    • Tasks
  • Components & Props
    • Small components
    • Passing data to a component
    • Loops in JSX
    • Tasks
  • Stateful components
    • Handling events
    • Components with internal state
    • Talking to a parent component
    • Smart and dumb components
    • Before the break
    • Tasks
  • Side-effects and context
    • Side-effects
    • Prop drilling
    • Using context
    • Tasks
  • What's next
    • Styling
    • Learning component's lifecycle
    • State Management
Powered by GitBook
On this page
  • Combining object types
  • Interfaces
  • Resources

Was this helpful?

  1. Typescript

Typing objects

Typing objects is just as simple as typing primitive values:

type Profiler = {
    logger?: string;
    start: Date;
    done(info?: string): boolean;
    run: () => void;
}

Properties of an object can be marked as optional with the ?.

Combining object types

Those types have common fields: _id, price, and category.

type Book = {
    _id: string;
    price: number;
    category: number;
    title: string;
    description: string;
}

type Pen = {
    _id: string;
    price: number;
    category: number;
    brand: string;
    type: string;
}

Let's create a separate type for the common properties and rewrite the types:

type Product = {
    _id: string;
    price: number;
    category: number;
}

type Book = Product & {
    title: string;
    description: string;
}

type Pen = Product & {
    brand: string;
    type: string;
}

Interfaces

Interfaces are another way of creating custom types.

interface IProduct {
    _id: string;
    price: number;
    category: number;
}

interface IBook extends IProduct {
    title: string;
    description: string; 
}

interface IPen extends IProduct {
    brand: string;
    type: string;    
}

There are some very minor differences between type aliases and interfaces. In general interfaces seem to be more suitable for object-oriented code with classes.

Resources

PreviousBasic typesNextTyping functions

Last updated 5 years ago

Was this helpful?

Handbook: Interfaces
Handbook: Type aliases
Interface vs Type alias