Skip to content

Instantly share code, notes, and snippets.

type Email = string & { __brand: "Email" };
const email = "example@org.hu";
function isValidEmail(input: string): input is Email {
return /@/.test(input);
}
function sendEmail(email: Email) {
console.log(email);
// send email
type RgbTuple = Tuple<3, number>;
// ^? type RgbTuple = readonly [number, number, number]
const red: RgbTuple = [255, 0, 0];
type Tuple<Length, Type, Acc extends Type[] = []> = Acc["length"] extends Length
? Readonly<Acc>
: Tuple<Length, Type, [...Acc, Type]>;
function add(a: number, b: number): number {
return a + b;
}
type Test = typeof add;
// ^ = type Test = (a: number, b: number) => number
type Test2 = ReturnType<typeof add>;
// ^ = type Test2 = number
//
type Locations = 'Zurich' | 'Warsaw' | 'London';
function getCountryLocation(location: Locations) {
switch (location) {
case 'Zurich':
return 'Switzerland';
case 'Warsaw':
return 'Poland';
case 'London':
return 'UK';
type GapType = 'margin' | 'padding';
type PositionType = 'top' | 'right' | 'bottom' | 'left';
type GapCss = `${GapType}-${PositionType}`;
// GapCss: "margin-top" | "margin-right" | "margin-bottom" | "margin-left" | "padding-top" | "padding-right" | "padding-bottom" | "padding-left"
//
type SizeType = 'rem' | 'em' | 'px' | '%' | 'vh' | 'vw' | '';
type SizeCss = `${number}${SizeType}`;
type Events = {
add: string;
remove: string;
move: string;
};
type EventKeys = keyof Events;
const userActions: OnEvent = {
onAdd: () => {},

Intuition

Approach

Complexity

  • Time complexity:
import { OtherComponent } from "./other-component";
import React, { useRef, ElementRef } from "react";
// Pass it in via typeof!
type OtherComponentRef = ElementRef<typeof OtherComponent>;
const Component = () => {
const ref = useRef<OtherComponentRef>(null);
return <OtherComponent ref={ref}>Hello</OtherComponent>;
};
import React, { forwardRef } from "react";
// Declare a type that works with generic components
type FixedForwardRef = <T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactElement
) => (props: P & React.RefAttributes<T>) => React.ReactElement;
// Cast the old `forwardRef` to the new one
export const fixedForwardRef = forwardRef as FixedForwardRef;
# Sliding window algorithm
#
# @param {String} s
# @return {Integer}
def length_of_longest_substring(s)
max = 0
subset = []
s.each_char do |char|
if subset.include?(char)