Skip to content

Instantly share code, notes, and snippets.

@sunil-bagde
Created February 11, 2022 18:10
Show Gist options
  • Save sunil-bagde/1c3f21949831c7dc4e50f1e6e26fa812 to your computer and use it in GitHub Desktop.
Save sunil-bagde/1c3f21949831c7dc4e50f1e6e26fa812 to your computer and use it in GitHub Desktop.

Simple typescript with react v4.3

const greeting: string = "Hello typescript";

const year: number = 2022;

const addTwoNumber = (a:number, b:number): number => a + b;

function addTwoNumber(a: number, b:number): number {
  return a + b;
}
interface User {
  id: string;
  name: string
  age: number,
  email: string
}
const getUserById = (id: string): User => ({
  id,
  name: "Mich",
  age: 33,
  email : "mich@gmail.com"
});

Optional property

interface Book {
  id: string;
  name: string;
  releaseDate?: Date; // Optional ?:
}

const getBookById(id: string) : Book => ({
  id,
  name: "Typescript",
})

const getBookByIdWithDate(id: string) : Book => ({
  id,
  name: "Typescript",
  releaseDate: new Date(),
})

Array and Tuple

const users: string[] = [
  "Mich",
  "Vishal",
  "Pranav"
];

const listOfNum: number[] = [1,2,4];

const nums: Array<number> = [1,2,3]

const stringOrNumber: (string|number)[] = [1, 'hello', 2022, "Michael"]

// Tuples -> fixed length array
const tuple: [number, string] =  [2022, "Why"];
// ☝️ first has to be a number and second has to be string

const wrong: [number, string] = ['why', 2022]; // wrong

Literals and Enums

 // Literals Type

const windOrLoose = (): "Win" | "Loose" => Math.random() < 0.5 ?  "Win" : "Loose";

enum UserResponse {
  No = 0,
  Yes = 1,
}
enum UserResponse1 {
  No = "No",
  Yes = "Yes",
}
function respond(recipient: string, message: UserResponse): void {
  // ...
}
function respond1(recipient: string, message: UserResponse1): void {
  // ...
}

respond("Princess Caroline", UserResponse1.Yes)
// More https://www.typescriptlang.org/docs/handbook/enums.html#string-enums

void , null , undefined

// Void
const logger = ( something: unknown ) : void => console.log(something)
// null

interface User {
  id: string;
  email: string;
  name: string|null;
  age: number|null
}
const createUser = (email: string): User =>({
  id: 'new-id',
  email,
  name: null,
  age:null,
})
const user = createUser("hello@email.com")

any and unknown

 // any dont user
const logger = ( something: unknown): void => {
  if(typeof something === string) {
    console.log(something.toUpperCase())
  } else {
    console.log(something)
  }
}
logger("Typescript");
logger({ foo: 'bar'})

Interfaces and Type Aliases

Unions and Intersection

interface UserCreateEvent = {
  eventType: 'USER_CREATED',
  parameters: {
    id: string,
    name: string,
    email: string
  }
}
interface UserDeletedEvent = {
  eventType: 'USER_DELETED',
  parameters: {
    id: string,
  }
}

type BetterUserEvent = UserCreateEvent | UserDeletedEvent;

const handleBetterUserEvent = (event: BetterUserEvent) => {
  if(event.eventType === 'USER_CREATED') {
    console.log(event.parameters.email);
    return
  }
  if(event.eventType === 'USER_DELETED') {
    console.log(event.parameters.id);
    console.log(event.parameters.name); // will error
    return
  }
}

Never

Intersections

type Dictionary = {
  [key:string]: string
}

// e.g
const dict: Dictionary = {
  foo: 'bar',
  bar: 'baz'
}

type OtherDictionary = Record<string, string>

type UnknownRecord = Record<PropertyKey, unknown>;

Generics

interface Box<T> {
  contents: T
}
const boxOfStrings: Box<string[]> = {
  contents: ['hello', 'Typescript']
}
const boxOfString: Box<string> = {
  contents: 'hello'
}

const boxOfNumbers: <number[]> = {
  contents: [1,2,3]
}

const identity = <T>(x: T): T => x

const rendomElement = <T>(xs: T[]): T => {
  const rendomeIndex  = Math.floor(x: Math.random() * xs.length);
  return xs[rendomeIndex];
}
const a = randomElement([1,2,4]);
const b = randomElement(["a", "b"]);
// 2nd

const rendomElement = <T, U>(xs: T[], ys: U[]): T|U => {
  const rendomeIndex  = Math.floor(x: Math.random() * xs.length);
  const useX = Math.random() < 0.5;
  return useX ? xs[rendomeIndex] : ys [randomIndex];
}
const a = randomElement([1,2,4], ['a', 'b']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment