Skip to content

Instantly share code, notes, and snippets.

View phanshiyu's full-sized avatar

Phan Shi Yu phanshiyu

View GitHub Profile
function useRunImmediatelyOnChange(effect: () => void, deps: unknown[] = []) {
if (!deps.length) deps.push(true);
const depsRef = React.useRef<unknown[]>();
if (depsRef.current && depsRef.current.length !== deps.length) {
throw new Error("Length of dependency list should not change");
}
for (let i = 0; i < deps.length; i += 1) {
@phanshiyu
phanshiyu / get-valid-paths-in-obj.ts
Last active April 27, 2024 05:39
[Typescript] Get valid paths in object
type Field<T extends Record<string, any> | Array<any>> = Exclude<
T extends Array<infer ArrayItem>
?
| `[${number}]`
| (ArrayItem extends Record<string, any> | Array<any>
? Field<ArrayItem> extends infer NextValue
? NextValue extends string
? `[${number}]${NextValue extends `[${string}` ? NextValue : `.${NextValue}`}`
: never
: never
@phanshiyu
phanshiyu / noExtraProps.ts
Created April 26, 2024 09:53
[Typescript] Preventing extra properties when using generics in function
type Person = {
name: string;
certificate: Record<string, any>;
};
// generic usage here is desired, cos it allows the return type to resolve to something more specific
function createPerson<T extends Person>(p: T): T { ... }
// kyle will have certificate.course typed as "string"
const kyle = createPerson({
@phanshiyu
phanshiyu / override.ts
Created April 25, 2024 15:34
Typescript - Override properties of object/object that allows extra keys (union with Record<string, any)
/** Overrides properties in the Target */
type Override<
Target extends Record<string, unknown>,
OverrideWith extends Record<string, unknown>
> = Target extends infer Meat & Record<string, any>
? Omit<Meat, keyof OverrideWith> & OverrideWith & Record<string, any>
: Target extends Record<string, unknown>
? Omit<Target, keyof OverrideWith> & OverrideWith
: never;
@phanshiyu
phanshiyu / handler.ts
Created October 14, 2022 10:19
aws lambda mutipart example with pngquant
import PngQuant from 'pngquant'
import { APIGatewayEvent, APIGatewayProxyResult, ScheduledEvent } from 'aws-lambda'
import busboy from 'busboy'
import { createReadStream, createWriteStream } from 'fs'
import { tmpdir } from 'os'
import path from 'path'
import { Stream } from 'stream'
export const handler = async (
event: APIGatewayEvent