Created
August 19, 2023 00:34
-
-
Save webbower/fd63f17cd9b0a15a5dc329562bb9b2c9 to your computer and use it in GitHub Desktop.
TypeScript Magic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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