Skip to content

Instantly share code, notes, and snippets.

@webbower
Created August 19, 2023 00:34
Show Gist options
  • Save webbower/fd63f17cd9b0a15a5dc329562bb9b2c9 to your computer and use it in GitHub Desktop.
Save webbower/fd63f17cd9b0a15a5dc329562bb9b2c9 to your computer and use it in GitHub Desktop.
TypeScript Magic
/* Combined Union Type + Array of allowed values */
const ServerEnvironments = ['development', 'test', 'stage', 'production'] as const;
// equivalent to `type ServerEnvironments = 'development' | 'test' | 'stage' | 'production'
type ServerEnvironments = typeof ServerEnvironments[number];
const serverEnv: ServerEnvironments = 'development';
const isValidServerEnv = (env: string): env is ServerEnvironments => ServerEnvironments.include(env);
const parseServerEnv = (env: string = process.env.SERVER_ENV): ServerEnvironments => isValidServerEnv(env) ? env : ServerEnvironments[2];
/* Non-class constructor + instance combined type + value */
type Person = { name: string; age: number; married: boolean; }
type PersonConstructor = {
(rawData: Record<string, unknown>) => Person;
fromJSON(jsonData: Record<string, unknown>) => Person;
};
const Person: PersonConstructor = ({ name, age, married = false }) => ({ name, age, married });
Person.fromJSON = () => {...};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment