Skip to content

Instantly share code, notes, and snippets.

@carlrip
carlrip / App.tsx
Created February 23, 2021 05:38
Update Requests with React Query
import React from "react";
import { useQuery, useMutation } from "react-query";
type Person = {
id: number;
firstName: string;
lastName: string;
};
async function getPerson({ queryKey }: { queryKey: [string, { id: number }] }) {
@carlrip
carlrip / App.tsx
Last active February 11, 2023 13:12
Cancelling fetch in React and TypeScript
import React from "react";
type Character = {
name: string;
};
interface PromiseWithCancel<T> extends Promise<T> {
cancel: () => void;
}
function getCharacter(id: number) {
@carlrip
carlrip / index.ts
Created December 17, 2019 18:31
Omit type - change to base type
type Person = {
id: number;
name: string;
mobile: string;
email: string;
age: number;
}
// PersonWithoutContactDetails automatically becomes { id: number; name: string; age: number;}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:30
Omit type
type PersonWithoutContactDetails = Omit<Person, "mobile" | "email"> // { id: number; name: string; }
@carlrip
carlrip / index.ts
Created December 17, 2019 18:29
Omit utility type - base type
type Person = {
id: number;
name: string;
mobile: string;
email: string;
}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:28
Nullish coalescing
function getPersonScore(id: number): number {
const person: Person = getPerson(id);
return person.score ?? 0;
}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:27
Nullish coalescing - before
type Person = {
id: number;
name: string;
score?: number;
}
function getPersonScore(id: number): number {
const person: Person = getPerson(id);
return person.score; // 💥 - Type error - Type 'number | undefined' is not assignable to type 'number'
}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:26
optional chaining
function getPersonPostcode(id: number) {
const person: Person = getPerson(id);
return person.address?.zipcode; // returns `undefined` if `address` is `undefined`
}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:25
optional chaining - before
type Person = {
id: number;
name: string;
address?: Address;
}
type Address = {
line1: string;
line2: string;
line3: string;
zipcode: string;
@carlrip
carlrip / index.ts
Created December 17, 2019 18:24
const assertions - literals
const Status = {
Loading: "LOADING",
Loaded: "LOADED",
} as const ;
logStatus(Status.Loading); // Type is "LOADING"