08 2022 档案
摘要:For example: const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla',
阅读全文
摘要:For example: interface Todo { title: string description: string } const todo: MyReadonly<Todo> = { title: "Hey", description: "foobar" } todo.title =
阅读全文
摘要:For example: interface Todo { title: string description: string completed: boolean } type TodoPreview = MyPick<Todo, 'title' | 'completed'> const todo
阅读全文
摘要:Reuse existing instances when working with identical objects The flyweight pattern is useful when you're creating a huge number of objects, which coul
阅读全文
摘要:You're given an array of integers and another array of three distinct integers. The first array is guaranteed to only contain integers that are in the
阅读全文
摘要:Step 7: Tests for Types The assertion type code need to be tested just as the normal code. export function isITeam(arg: any): arg is ITeam { /** * { i
阅读全文
摘要:Step1 & 2 for converting a js app to ts Step 3. Turn on "noImplicitAny" and even more strict mode Step 4. ESLint for Typescript Step5. Local types ove
阅读全文
摘要:Step 5: Types at Runtime This problem often happens when APi return the data. let cachedAllTeamsList: Promise<ITeam[]>; export async function getAllTe
阅读全文
摘要:Step5. Local types override You can find many @types package along with the library you use. But the problem is that those @types might contain bugs b
阅读全文
摘要:Step 4: ESLint We need to install ESLint tools for Typescript. yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser .eslintrc file:
阅读全文
摘要:Step 3: Turn on "noImplicitAny" From previous steps, we allow implicit any: https://www.cnblogs.com/Answer1215/p/16634618.html Now, we need to turn on
阅读全文
摘要:1. Compiling in "loose mode" Start with all tests passing Rename all .js to .ts, allowing implicit any Fix only things that are not type-checking, or
阅读全文
摘要:Source: https://javascriptpatterns.vercel.app/patterns/performance-patterns/browser-hints Prefetch The `prefetch` browser hint can be used to fetch re
阅读全文
摘要:Source: https://javascriptpatterns.vercel.app/patterns/performance-patterns/route-based-splitting If you're using react-router for navigation, you can
阅读全文
摘要:Source: https://javascriptpatterns.vercel.app/patterns/performance-patterns/import-on-visibility One way to dynamically import components on interacti
阅读全文
摘要:Source : https://javascriptpatterns.vercel.app/patterns/react-patterns/compound-pattern A compound compoennt usage looks like this: import React from
阅读全文
摘要:Docs The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to firs
阅读全文
摘要:Source: https://javascriptpatterns.vercel.app/patterns/design-patterns/prototype-pattern If you use factory pattern to create object: const createDog
阅读全文
摘要:In JavaScript, the factory pattern isn't much more than a function that returns an object without using the new keyword. ES6 arrow functions allow us
阅读全文
摘要:Source: https://javascriptpatterns.vercel.app/patterns/design-patterns/singleton-pattern With the Singleton Pattern, we restrict the instantiation of
阅读全文
摘要:Module pattern provide a way to have both public and private pieces with the export keyword. This protects values from leaking into the global scope o
阅读全文
摘要:import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at ru
阅读全文
摘要:function isError(err: any): err is Error { return err instanceof Error; } try { somethingRisky() } catch(err: unknown) { if (isError(err)) { console.l
阅读全文
摘要:In some ways // @ts-expect-error can act as a suppression comment, similar to // @ts-ignore. The difference is that // @ts-ignore will do nothing if t
阅读全文
摘要:CrudController: 查看代码 export const getOne = model => async (req, res) => { try { const doc = model .findOne({ createdBy: req.user._id, _id: req.params.
阅读全文
摘要:Each model controller: import { crudControllers } from '../../utils/crud' import { Item } from './item.model' export default crudControllers(Item) You
阅读全文
摘要:Model: import mongoose from 'mongoose' const itemSchema = new mongoose.Schema( { name: { type: String, required: true, trim: true, maxlength: 50 }, st
阅读全文
摘要:Model: import mongoose from 'mongoose' const itemSchema = new mongoose.Schema( { name: { type: String, required: true, trim: true, maxlength: 50 }, st
阅读全文
摘要:Example 1: import mongoose from 'mongoose' const itemSchema = new mongoose.Schema( { name: { type: String, required: true, trim: true, maxlength: 50 }
阅读全文
摘要:server.js: import itemRouter from './resources/item/item.router' export const app = express() app.use('/api/item', itemRouter) item.router.js import {
阅读全文
摘要:In VSCode, install REST Clinet Extension: Create API_EXAMPLE.http file in root folder: ### Get mock GET http://localhost:3000/data HTTP/1.1 ### Post m
阅读全文
摘要:type Corner = `${'top' | 'bottom'} - ${'left' | 'right'}` type Corner = Capitalize<`${'top' | 'bottom'} - ${'left' | 'right'}`> // "Top - left" | "Top
阅读全文
摘要:V3: type JSONValue = | string | number | boolean | null | JSONArray | JSONObject; type JSONArray = JSONValue[]; type JSONObect = { [k: string]: JSONVa
阅读全文
摘要:Let's see the unlabelled tuple type: type Address = [ number, string, string, number, ] function printAddress(...address: Address) { console.log(addre
阅读全文
摘要:List all the props with begin with "query" key in Document type queryTypes = Extract<keyof Document, `query${string}`> type queryyPoprDoc = { [Key in
阅读全文
摘要:Yarn workspace Add following lines to the package.json file "workspaces": [ "packages/*" ] And create folder call packages in the root folder. Somethi
阅读全文
摘要:type PartOfWindow = { [Key in | "document" | "navigator" | "setTimeout"]: Window[Key] } /* type PartOfWindow = { document: Document; navigator: Naviga
阅读全文
摘要:Blog: https://www.geeksforgeeks.org/es6-trampoline-function/ Stackoverflow problem for recursion: const sumBelow = (number, sum = 0) => ( number 0 ? s
阅读全文
摘要:Index Signature type Fruit = { name: string color: string mass: number } type Dict<T> = { [k: string]: T } // <- index signature const fruitCatalog: D
阅读全文
摘要:Indexed Access types provide a mechanism for retrieving part(s) of an array or object type via indices. We’ll look at how this kind of type works, and
阅读全文
摘要:For example we have a Webpack class: class WebpackCompiler { constructor(options: { amd?: false | { [index: string]: any } bail?: boolean cache?: | bo
阅读全文
摘要:function lotteryNum() { return (Math.round(Math.random() * 100) % 58) + 1; } function recordNumber(luckLotteryNumbers: readonly number[], num: number)
阅读全文
摘要:Extract is useful for obtaining some sub-part of a type that is assignable to some other type. type FavoriteColors = | "dark sienna" | "van dyke brown
阅读全文
摘要:Let’s study a few examples of extends scenarios and see if we can figure out whether it will evaluate to true or false 64 extends number . . . Answer:
阅读全文
摘要:keyof The keyof type query allows us to obtain type representing all property keys on a given interface. key can be string, number or Symbol. So what
阅读全文
摘要:From source: https://www.typescript-training.com/course/intermediate-v1/03-modules/ Things can sometimes get a bit tricky when consuming CommonJS modu
阅读全文
摘要:Stacking multiple things on an identifier interface Fruit { name: string mass: number color: string } const Fruit = { name: "banana", color: "yellow",
阅读全文
摘要:`namespace` is manily for the left over from the days where we’d refer to libraries through a single global variable. With this in mind, let’s not giv
阅读全文
摘要:When working with function parameters, we know that “inner scopes” have the ability to access “outer scopes” but not vice versa function receiveFruitB
阅读全文
摘要:Assume we have the following code: interface HasId { id: string } interface Dict<T> { [k: string]: T } function listToDict<T>(list: T[]): Dict<T> { co
阅读全文
摘要:const fruits = { apple: { color: "red", mass: 100 }, grape: { color: "red", mass: 5 }, banana: { color: "yellow", mass: 183 }, lemon: { color: "yellow
阅读全文
摘要:Add to global commands Add #! /usr/bin/env node to index.js chmod +x index.js Run ./index.js to test. ln -s <full_path_to_index.js_file>/index.js /usr
阅读全文
摘要:Our CLI can be run from anywhere on the system but we have a critical error. The script is trying to find a data.json file that is relative to where i
阅读全文
摘要:There are a handful of ways you can read and write to the File System in Node.js. We will look at readFileSync, readFile, and a promise based version
阅读全文
摘要:Node.js projects have two ways that you can import and export code into different files. This is through CommonJS (CJS) and ECMAScript modules (ESM).
阅读全文
摘要:Assumption: Run the testing code only if when the condition is match, otherwise, test will be ignored @Test void runTestIf() { System.out.print("Curre
阅读全文
摘要:// This is an input class. Do not edit. class Node { constructor(value) { this.value = value; this.prev = null; this.next = null; } } // Feel free to
阅读全文
摘要:The definite assignment !: operator is used to suppress TypeScript’s objections about a class field being used, when it can’t be proven1 that it was i
阅读全文
摘要:Requirements: function strBuilder(str) { return strBuilder; // TODO } var hello = strBuilder("Hello, "); var kyle = hello("Kyle"); var susan = hello("
阅读全文
摘要:value is Foo The first kind of user-defined type guard we will review is an is type guard. It is perfectly suited for our example above because it’s m
阅读全文
摘要:class UnreachableError extends Error { constructor(_nvr: never, message: string) { super(message) } } class Car { drive() { console.log("vroom") } } c
阅读全文
摘要:For the following class: class Car { make: string model: string year: number constructor(make: string, model: string, year: number) { this.make = make
阅读全文