Skip to content

Instantly share code, notes, and snippets.

@alii
Created September 6, 2021 17:24
Show Gist options
  • Save alii/cb1d37b93455f99ae807d04833c71252 to your computer and use it in GitHub Desktop.
Save alii/cb1d37b93455f99ae807d04833c71252 to your computer and use it in GitHub Desktop.
typescript fun with generics
// Was having some fun with TypeScript and built a signature for some theoretical
// object that could cast any type to any other type. This uses template literal types,
// generics, infer and mapped types.
import {Except} from 'type-fest';
type TypeofsTypes = {
string: string;
number: number;
bigint: BigInt;
boolean: boolean;
symbol: symbol;
undefined: undefined;
object: Record<string | number | symbol, unknown>;
function: (...args: unknown[]) => unknown;
};
type Typeofs = keyof TypeofsTypes;
type ToTypeofs<T> = Except<TypeofsTypes, 'object'> & {
object: {value: T};
};
type TO = 'to';
type SubtractTo<T extends string> = T extends `${TO}${infer X}` ? Uncapitalize<X> : never;
type AddTo<T extends string> = `${TO}${Capitalize<T>}`;
declare const handlers: {
[FromType in Typeofs]: {
[ToType in AddTo<Typeofs>]: (
from: TypeofsTypes[FromType]
) => ToTypeofs<TypeofsTypes[FromType]>[SubtractTo<ToType>];
};
};
handlers.string.toObject('hello');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment