Skip to content

Instantly share code, notes, and snippets.

@amit08255
Last active February 19, 2023 17:54
Show Gist options
  • Save amit08255/1de2d8d60ed88965b4d59abd2a8dbf68 to your computer and use it in GitHub Desktop.
Save amit08255/1de2d8d60ed88965b4d59abd2a8dbf68 to your computer and use it in GitHub Desktop.
TypeScript Cheatsheet

TypeScript Cheatsheet

Extracting and reusing return type of a function

declare function f1(): { a: number; b: string };
 
type T0 = ReturnType<() => string>;
type T1 = ReturnType<(s: string) => void>;
type T2 = ReturnType<<T>() => T>;
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T4 = ReturnType<typeof f1>; // reusing return type of function f1 in T4

Extracting and reusing parameter type of a function

const mutateFnc:Client['mutation'] = null; // Creating dummy function type of function same as of external lib.

type MutationParams = Parameters<typeof mutateFnc>; // Extracting function parameter types


// Reusing function parameter types and return types
const mutationWithNotify = (successMessage: string) => <Data = any, Variables extends object = {}>(a:MutationParams[0], b?:Variables, c?:MutationParams[2]):ReturnType<typeof mutateFnc> => {
    return client.mutation();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment