Skip to content

Instantly share code, notes, and snippets.

@Wintus
Last active May 3, 2023 16:10
Show Gist options
  • Save Wintus/741db3cda1e699dc2686baadab56adec to your computer and use it in GitHub Desktop.
Save Wintus/741db3cda1e699dc2686baadab56adec to your computer and use it in GitHub Desktop.
TypeScript: type-level programming and some helpers
import { DeepNonNullable, Falsy, isFalsy } from "utility-types";
export const isNullable = <T>(value: Nullable<T>): value is null | undefined => value == null;
export const assertIsDefined = <T>(val: T): asserts val is NonNullable<T> => {
if (isNullable(val)) {
throw new Error(`Expected 'val' to be defined, but received ${val}`);
}
};
type Truthy<T> = Exclude<T, Falsy>;
export const assertTruthy = <T>(value: T, message?: string): asserts value is Truthy<T> => {
if (isFalsy(value)) {
throw new Error(message);
}
};
type Async<F extends (...args: any[]) => any> = (...args: Parameters<F>) => Promise<ReturnType<F>>;
type Defined<T> = Exclude<T, undefined>;
// https://github.com/Microsoft/TypeScript/issues/27024
export type Equals<X, Y> =
(<T>() => T extends X ? 1 : 0) extends
(<T>() => T extends Y ? 1 : 0) ? true : false;
export type IndexSignature<O extends object> = {
[P in keyof O]: O[P];
};
type InferIntersection<I, T> = I extends (T & infer U) ? U : never;
type Nullable<T> = T | null;
const nonNull = <T>(x?: Nullable<T>): boolean = x != null;
type ShouldNotBeNull<T> = 1 extends (T extends null ? 1 : never) ? never : T;
function f<K>(x: ShouldNotBeNull<K>): void { x; }
f<number>(1)
// @ts-expect-error: TS2345
f<number|null>(1)
@Wintus
Copy link
Author

Wintus commented Nov 6, 2019

type AndExtends<T, A, B> = any extends T ? A : B
type AndExtends<T, A, B> = A | B; // T != any

@Wintus
Copy link
Author

Wintus commented May 3, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment