### Initial Repository Setup and Dependency Installation Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Steps to set up the repository after cloning, including navigating into the project directory, ensuring the main branch is checked out, and installing top-level dependencies and bootstrapping packages using Yarn. ```Shell cd sfdx-dev-packages git checkout -t origin/main yarn ``` -------------------------------- ### Install Yarn Globally Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Installs Yarn globally using npm, which is required for managing Node.js dependencies in this repository. ```Shell npm install --global yarn ``` -------------------------------- ### Bootstrap Packages with Yarn Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Runs `yarn install` on each package and symlinks packages within the monorepo. This command should be run as the first step after making changes in the modules or to `package.json` dependencies. ```Shell yarn bootstrap ``` -------------------------------- ### Commit with Commitizen Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Installs Commitizen globally and then uses it to format commit messages, ensuring adherence to enforced commit message formats. ```Shell yarn global add commitizen git cz ``` -------------------------------- ### Accessing Nested Properties with get* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `get*` suite of functions search an `unknown` target value for a given path. Search paths follow the same syntax as `lodash`'s `get`, `set`, `at`, etc. These functions are more strictly typed, however, increasingly the likelihood that well-typed code stays well-typed as a function's control flow advances. ```typescript // imagine response json retrieved from a remote query const response = { start: 0, length: 2, results: [{ name: 'first' }, { name: 'second' }] }; const nameOfFirst = getString(response, 'results[0].name'); // type of nameOfFirst = string ``` -------------------------------- ### Type-Safe JSON Processing with Bare TypeScript Type Guards Source: https://github.com/forcedotcom/ts-types/blob/main/README.md This example shows how to achieve type and null safety in TypeScript using explicit type guards. While effective, this approach can lead to verbose and less readable code due to the numerous conditional checks required for each data access. ```typescript const json = JSON.parse(response.body); if (json === null && typeof json !== 'object') throw new Error('Unexpected json data type'); let results = json.results; if (!Array.isArray(results)) results = []; results.forEach(item => { const id = item.id; if (typeof id !== 'string') throw new Error('Unexpected item id data type'); db.save(id, item); }); ``` -------------------------------- ### Chained Type-Safe JSON Processing with ts-types Library Source: https://github.com/forcedotcom/ts-types/blob/main/README.md This example shows a more compact way to process JSON data using chained `ts-types` functions. It achieves robust type and null checking with a syntax not much more complex than the original unsafe JavaScript, highlighting the library's ability to simplify complex type-safe operations. ```typescript asJsonArray(ensureJsonMap(JSON.parse(response.body)).results, []).forEach(item => { const record = ensureJsonMap(item); db.save(ensureString(record.id), record); }); ``` -------------------------------- ### Run Tests with Yarn Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Executes the `yarn test` command on each of the packages within the `packages` directory. ```Shell yarn test ``` -------------------------------- ### Run Linter with Yarn Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Executes the `yarn lint` command on each of the packages within the `packages` directory to ensure code style and quality. ```Shell yarn lint ``` -------------------------------- ### Compile Packages with Yarn Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Executes the `yarn compile` command on each package within the `packages` directory. ```Shell yarn compile ``` -------------------------------- ### Clean Packages with Yarn Source: https://github.com/forcedotcom/ts-types/blob/main/DEVELOPING.md Runs `yarn clean` on each package. The `yarn clean-all` command can also be used to clean up `node_modules` directories. ```Shell yarn clean ``` -------------------------------- ### TypeScript Utility Types Reference Source: https://github.com/forcedotcom/ts-types/blob/main/README.md A reference for commonly used utility types provided by the library, designed to augment standard TypeScript types for more concise code. Please see the generated API documentation for the complete set of provided types. ```APIDOC Optional: An alias for the union type `T | undefined`. NonOptional: Subtracts `undefined` from a type `T`, when `T` includes `undefined` as a union member. Nullable: An alias for the union type `Optional`, or `T | null | undefined`. `NonNullable` is a TypeScript built-in that subtracts both `null` and `undefined` from a type `T` with either as a union member. Dictionary: An alias for a `string`-indexed `object` of the form `{ [key: string]: Optional }`. KeyOf: An alias for the commonly needed yet verbose `Extract`. AnyJson: A union type of all valid JSON values, equal to `JsonPrimitive | JsonCollection`. JsonPrimitive: A union of all valid JSON primitive values, qual to `null | string | number| boolean`. JsonMap: A dictionary of any valid JSON value, defined as `Dictionary`. JsonArray: An array of any valid JSON value, defined as `Array`. JsonCollection: A union of all JSON collection types, equal to `JsonMap | JsonArray`. ``` -------------------------------- ### Simplified Type-Safe JSON Processing with ts-types Library Source: https://github.com/forcedotcom/ts-types/blob/main/README.md This snippet demonstrates the use of `ts-types` library functions like `ensureJsonMap` and `asJsonArray` to simplify type-safe JSON processing. These functions reduce boilerplate by handling type narrowing and error raising, making the code more concise and readable while maintaining robustness. ```typescript const json = ensureJsonMap(JSON.parse(response.body)); const results = asJsonArray(json.results, []); results.forEach(item => { record = ensureJsonMap(record); db.save(ensureString(record.id), record); }); ``` -------------------------------- ### Concise but Unsafe JSON Processing in JavaScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md This snippet demonstrates a typical JavaScript approach to parsing and processing JSON data. While concise, it lacks null-safety and type-safety, making it prone to runtime errors when dealing with unexpected data structures. ```javascript JSON.parse(response.body).results.forEach(item => db.save(item.id, item)); ``` -------------------------------- ### Enhanced Object Iteration Utilities in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md This suite of functions offers type-convenient alternatives to built-in `Object.keys`, `Object.entries`, and `Object.values`. They provide improved `keyof` typings during iteration and can filter out `undefined` or `null` values, making object property processing more robust and type-safe. ```typescript const pets: Dictionary = { fido: 'dog', bill: 'cat', fred: undefined }; // note that the array is typed as [string, string] rather than [string, string | undefined] function logPet([name, type]: [string, string]) { console.log('%s is a %s', name, type); } definiteEntriesOf(pets).forEach(logPet); // fido is a dog // bill is a cat ``` -------------------------------- ### Narrowing with as* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `as*` suite of functions accepts a broadly typed variable (e.g., `unknown` or `object`) and optionally returns a narrowed type after validating it with a runtime test. If the test is negative or if the value was not defined (i.e. `undefined` or `null`), `undefined` is returned instead. ```typescript // some function that takes a string or undefined function upperFirst(s: Optional): Optional { return s ? s.charAt(0).toUpperCase() + s.slice(1) : s; } // type of value -> unknown const name = upperFirst(asString(value)); // type of name -> Optional ``` -------------------------------- ### Coercing to JSON-Specific Types with coerce* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `coerce` suite of functions accept values of general types and narrow their types to JSON-specific values. They are named with the `coerce` prefix to indicate that they do not perform an exhaustive runtime check of the entire data structure -- only shallow type checks are performed. As a result, _only_ use these functions when you are confident that the broadly typed subject being coerced was derived from a JSON-compatible value. If you are unsure of an object's origins or contents but want to avoid runtime errors handling elements, see the `to*` set of functions. ```typescript const response = coerceJsonMap(JSON.parse(await http.get('http://example.com/data.json').body)); // type of response -> JsonMap ``` -------------------------------- ### Type-Safe JSON Narrowing with to* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `to*` suite of functions provides a type-safe alternative to `coerce*` functions for JSON narrowing. These functions ensure JSON compatibility by performing a deep clone of the subject argument, omitting non-JSON compatible properties like functions, as demonstrated by `toJsonMap`. ```typescript const obj = { name: 'example', parse: function(s) { return s.split(':'); } }; const json = toJsonMap(obj); // type of json -> JsonMap // json = { name: 'example' } // notice that the parse function has been omitted to ensure JSON-compatibility! ``` -------------------------------- ### Narrowing with has* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `has*` suite of functions both tests for the existence and type-compatibility of a given value and, if the runtime value check succeeds, narrows the type to a view of the original value's type intersected with the tested property (e.g. `T & { [_ in K]: V }` where `K` is the test property key and `V` is the test property value type). ```typescript // type of value -> unknown if (hasString(value, 'name')) { // type of value -> { name: string } // value can be further narrowed with additional checks if (hasArray(value, 'results')) { // type of value -> { name: string } & { results: unknown[] } } else if (hasInstance(value, 'error', Error)) { // type of value -> { name: string } & { error: Error } } } ``` -------------------------------- ### Narrowing with ensure* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `ensure*` suite of functions narrow values' types to a definite value of the designated type, or raises an error if the value is `undefined` or of an incompatible type. ```typescript // type of value -> unknown try { const s = ensureString(value); // type of s -> string } catch (err) { // s was undefined, null, or not of type string } ``` -------------------------------- ### Narrowing with is* Functions in TypeScript Source: https://github.com/forcedotcom/ts-types/blob/main/README.md The `is*` suite of functions accepts a broadly typed variable (e.g., `unknown` or `object`) and returns a boolean type-predicate. This predicate is useful for narrowing the variable's type within conditional scopes. ```typescript // type of value -> string | boolean if (isString(value)) { // type of value -> string } // type of value -> boolean ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.