Skip to content

TypeScript

Comments

  • ignore a rule for the whole file

    /* eslint-disable rule-name */
    // @ts-nocheck (ignores the whole file)
    

  • ignore the rule for one line

/* eslint-disable-next-line rule-name */

// @ts-ignore (ignores one line)

Checking types

instanceof vs typeof

JS built-ins

  • instanceof for custom types
  • typeof for the simple built-in types

User Defined Type Guards

Return type isn't a boolean!

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Type Generation

Strings

Convert something to a string

String(123)

Enums

Generics

  • Inferred generic: (from the params)
  • example: React.useState()
    • explicitly: React.useState<UnknownObject>({})

React and TS

https://stackoverflow.com/questions/58123398/when-to-use-jsx-element-vs-reactnode-vs-reactelement

Return type

JSX.Element or React.ReactElement?

React.ReactElement works for an array of functions??

React.ReactNode

Type of a React "callable"

interface ComponentProps {
    id: number;   
}

const renderRoutes = (PassedComponent: React.ComponentType <ComponentProps>) => {
    return <PassedComponent 
}

Functions

type GreetFunction = (a: string) => void;

Click event

(event: React.MouseEvent<HTMLElement>) => void

Importing a type that's the same name as the class

When working with progressbar.js, I was getting errors

When I tried importing the Shape,

import ProgressBar, { PathDrawingOptions, Shape } from "progressbar.js";

I had to use typeof Shape because I was importing the class Shape rather than the type

Solution

There's a separate import for the Shape

import type Shape from "progressbar.js/shape";

Rest parameter

declare keyword

Example: importing from a JS library

Declare that some variable that you has this type

declare let module: any;

declare const module = { doSomething: () => boolean }

Last update: 2022-09-23