Skip to content

Instantly share code, notes, and snippets.

@guz-anton
Last active June 26, 2023 13:58
Show Gist options
  • Save guz-anton/4b9f4d1394eeb58510a27128fe22f88d to your computer and use it in GitHub Desktop.
Save guz-anton/4b9f4d1394eeb58510a27128fe22f88d to your computer and use it in GitHub Desktop.
Types collection
type CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`
? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`
: Lowercase<S>
type KeysToCamelCase<T> = {
[K in keyof T as CamelCase<string & K>]: T[K]
}
type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ?
`${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` :
S
type KeysToSnakeCase<T> = {
[K in keyof T as CamelToSnakeCase<string & K>]: T[K]
}
// https://sharegpt.com/c/OYNgU0C
type X = {
a: () => string;
b: () => number;
};
type Resolved<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => infer R ? R : T[K];
};
type Y = Resolved<X>;
type Y = {
a: string;
b: number;
}
// https://stackoverflow.com/a/68526558/1402890
type D1 = 0|1;
type D3 = D1|2|3;
type D5 = D3|4|5;
type D9 = D5|6|7|8|9;
type Hours = `${D9}` | `${D1}${D9}` | `2${D3}`;
type Minutes = `${D5}${D9}`;
type Time = `${Hours}:${Minutes}`;
// https://hacklewayne.com/typescript-convert-union-to-tuple-array-yes-but-how
type Contra<T> =
T extends any
? (arg: T) => void
: never;
type Cov<T> =
T extends any
? () => T
: never;
type InferContra<T> =
[T] extends [(arg: infer I) => void]
? I
: never;
type PickOne<T> = InferContra<InferContra<Contra<Contra<T>>>>;
const t31: PickOne<'a'|'b'> = 'b';
type Union2Tuple<T> =
PickOne<T> extends infer U
? Exclude<T, U> extends never
? [T]
: [...Union2Tuple<Exclude<T, U>>, U]
: never;
const t32: Union2Tuple<'a'|'b'|'c'|'d'|'e'> = ['a', 'b', 'c', 'd', 'e'];
// ### ------------------------------------
type TupleUnion<U extends string, R extends any[] = []> = {
[S in U]: Exclude<U, S> extends never ? [...R, S] : TupleUnion<Exclude<U, S>, [...R, S]>;
}[U];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment