Skip to content

Commit

Permalink
remove duplicated work
Browse files Browse the repository at this point in the history
  • Loading branch information
DDDDDanica committed Feb 28, 2024
1 parent 0a2b7c4 commit c87162c
Showing 1 changed file with 0 additions and 295 deletions.
295 changes: 0 additions & 295 deletions docs/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,41 +35,6 @@ function createExampleMiddleware<
>(exampleParam): JsonRpcMiddleware<Params, Result>
```

#### Use `Partial` to type the accumulating variable in `reduce`
When using reduce in TypeScript, the accumulating variable's type can be difficult to define, especially when dealing with optional properties or incomplete objects. In such cases, using Partial allows you to start with an empty object and gradually add optional properties as needed. Here's an example:

``` typescript
interface User {
name: string;
age?: number; // optional property
email: string;
}
// Partial<User> would be:
type PartialUser = {
name?: string;
age?: number;
email?: string;
}
const users: User[] = [
{ name: "Alice", age: 25, email: "alice@example.com" },
{ name: "Bob", age: 30, email: "bob@example.com" },
];
const oldestUser = users.reduce((acc, user) => {
// acc starts as Partial<User> (empty object)
if (user.age && (acc.age === undefined || user.age > acc.age)) {
acc.age = user.age;
acc.name = user.name; // add additional properties as needed
}
return acc;
}, {} as Partial<User>); // initialize with empty object
console.log(oldestUser); // { name: "Bob", age: 30 }
```


#### Use `Omit` to reduce requirements
`Omit<T, K>` takes two generic types: `T` representing the original object type and `K` representing the property keys you want to remove. It returns a new type that has all the properties of T except for the ones specified in K. Here are some cases to use omit:
- Removing Unnecessary Properties:
Expand Down Expand Up @@ -103,42 +68,6 @@ const singleItemPayload = Omit<CartItem, "color" extends string ? "color" : neve
const cartPayload: singleItemPayload[] = [];
```
#### When augmenting an object type with `&`, remember to apply `Omit` to any overlapping property keys.
* `&` does not automatically overwrite overlapping entries like the spread (...) operator does: https://tsplay.dev/NDJ48W
```typescript
type Original = {
a: string;
b: number;
c: boolean;
}
type Augment = {
c: 'hello'
}
type NoOmit = Original & Augment // never
type UseOmit = Omit<Original, 'c'> & Augment // { a: string; b: number; c: 'hello'; }
```
* One edge case to be especially careful of is if an optional property is being overwritten. Unlike the above case, this will fail silently: https://tsplay.dev/m0OBxN
```typescript
type Original = {
a: string;
b: number;
c?: boolean;
}
type Augment = {
c?: 'hello'
}
type NoOmit = Original & Augment // { a: string; b: number; c?: undefined; }
```
#### Don't use `any`
* `any` doesn't actually represent "any type"; if you declare a value as `any`, it tells TypeScript to disable typechecking for that value anywhere it appears. This means the compiler won't warn you about potential type mismatches or errors, leading to hidden issues that might surface later in development or production.
* `any` is dangerous because it infects all surrounding and downstream code. For instance, if you have a function that is declared to return `any` which actually returns an object, all properties of that object will be `any`.
* Need to truly represent something as "any value"? Use `unknown` instead.
#### Avoid type assertions, or explain their purpose whenever necessary.
Type assertions inform TypeScript about a variable's actual type, using the `as` syntax or the angle bracket ``<Type>`` syntax.
While type assertions offer flexibility, they can bypass TypeScript's safety net. This means the compiler won't catch potential type mismatches, leaving you responsible for ensuring correctness.
Expand Down Expand Up @@ -250,229 +179,5 @@ async function removeAccount(address: Hex): Promise<KeyringControllerState> {
}
```

#### Prefer `as never` for empty types
never is more accurate for typing an empty container rather than a representation of its fully populated shape.
never is assignable to all types, meaning this practice will rarely cause compiler errors.

🚫
```typescript
export class ExampleClass<S extends BaseState> {
defaultState: S = {} as S;
...
}
obj.reduce(
(acc, [key, value]) => {
...
},
{} as Record<keyof typeof obj, Json>,
)
```
```typescript
export class ExampleClass<S extends BaseState> {
defaultState: S = {} as never;
...
}
obj.reduce<Record<keyof typeof obj, Json>>(
(acc, [key, value]) => {
...
},
{} as never,
)
```

#### Prefer `as const`
🚫
```typescript
const templateString = `Failed with error message: ${error.message}` // Type 'string'
export const PROVIDER_ERRORS = {
limitExceeded: () =>
({
jsonrpc: '2.0',
id: IdGenerator(),
error: {
code: -32005,
message: 'Limit exceeded',
},
}),
...
}
/** evaluates to:
{
jsonrpc: number;
id: number;
error: {
code: number;
message: string;
};
}
*/
export const SUPPORTED_NETWORK_CHAINIDS = {
MAINNET: '0x1',
BSC: '0x38',
OPTIMISM: '0xa',
POLYGON: '0x89',
AVALANCHE: '0xa86a',
ARBITRUM: '0xa4b1',
LINEA_MAINNET: '0xe708',
};
// evaluates all values to `string`
```

```typescript
const templateString = `Failed with error message: ${error.message}` as const // Type 'Failed with error message: ${typeof error.message}'
export const PROVIDER_ERRORS = {
limitExceeded: () =>
({
jsonrpc: '2.0',
id: IdGenerator(),
error: {
code: -32005,
message: 'Limit exceeded',
},
} as const),
...
}
/** evaluates to:
{
jsonrpc: '2.0';
id: ReturnType<IdGenerator>;
error: {
code: -32005;
message: 'Limit exceeded';
};
}
*/
export const SUPPORTED_NETWORK_CHAINIDS = {
MAINNET: '0x1',
BSC: '0x38',
OPTIMISM: '0xa',
POLYGON: '0x89',
AVALANCHE: '0xa86a',
ARBITRUM: '0xa4b1',
LINEA_MAINNET: '0xe708',
} as const;
```

Exceptions:
🚫
```typescript
// This isn't necessary because the string literal is already considered a const by the compiler.
const walletName = 'metamask' as const;
this.messagingSystem.registerActionHandler(
`${name}:call` as const,
...
);
```

```typescript
const walletName = 'metamask';
this.messagingSystem.registerActionHandler(
`${name}:call`,
...
);
```


## **Language features**
#### Prefer the nullish coalescing operator `??`
* `??` guarantees that the left-hand operand is nullish but not falsy, which is both safer and reduces cognitive overhead for reviewers.
* Using `||` leads reviewers to assume that ?? was intentionally avoided, forcing them to consider cases where the left-hand operand is falsy. This should never happen if the left-hand operand is guaranteed to be nullish and not falsy.

#### Prefer negation (`!`) over strict equality checks for `undefined`, but not for `null`.
* Unlike with vanilla JavaScript, in TypeScript, we can rely on type inference and narrowing to correctly handle `null` checks without using strict equals(`===`).
* This does not apply if the `null` check needs to exclude falsy values.
* Because our codebase usually uses `undefined` for empty values, if a `null` is used, it should be assumed to be an intentional choice to represent an expected exception case or a specific class of empty value.
#### `Object.entries`
* `Object.keys` and `Object.entries` both type the object keys (index signature) as `string` instead of `keyof typeof` obj. An annotation or assertion is necessary to accurately narrow the index signature.
* Strong typing for the `entries` operation using generic arguments is unavailable, as the generic parameter for `Object.entries` only allows typing the object's values.
🚫
```typescript
Object.entries<Json>(state).forEach(([key, value]) => {
...
}
```
```typescript
(Object.keys(state) as (keyof typeof state)[]).forEach((key) => {
...
}

Object.entries(state).forEach(([key, value]): [keyof typeof state, Json]) => {
...
}
```
#### `Array.prototype.reduce`
* Use the generic argument to type the fully populated accumulator.
* Type the initial value of the accumulator object as `never`.
🚫
```typescript
Object.entries(state).reduce(
(acc, [key, value]: [keyof typeof state, Json]) => {
...
},
{} as Record<keyof typeof state, Json>,
)
Object.entries(state).reduce<Partial<Record<keyof typeof state, Json>>>(
(acc, [key, value]: [keyof typeof state, Json]) => {
...
},
{},
) as Record<keyof typeof state, Json>
```
```typescript
Object.entries(state).reduce<Record<keyof typeof state, Json>>(
(acc, [key, value]: [keyof typeof state, Json]) => {
...
},
{} as never,
)
```
#### Function supertype
🚫
```typescript
type AnyFunction = (...args: any[]) => any;

// Safe to use only if function params are guaranteed to be fully variadic with no fixed parameters.
type NeverFunction = (...args: never[]) => unknown;
```
```typescript
type FunctionSupertype = ((...args: never) => unknown) | ((...args: never[]) => unknown)
```
1. `(...args: never[]) => unknown`
The return type of this supertype function needs to be `unknown` (universal supertype), and the parameters need to be `never` (universal subtype).
This is because function parameters are contravariant, meaning `(x: SuperType) => T` is a subtype of `(x: SubType) => T`.
* There's an example of this in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#inferring-within-conditional-types).
* And here's a more detailed [reddit comment](https://www.reddit.com/r/typescript/comments/muyl55/comment/gv9ndij/?utm_source=share&utm_medium=web2x&context=3) on this topic.
2. `(...args: never) => unknown`
In general, array types of arbitrary length are not assignable to tuple types that have fixed types designated to some or all of its index positions (the array is wider than the tuple since it has less constraints).
This means that there's a whole subcategory of functions that `(...args: never[]) => unknown` doesn't cover: functions that have a finite number of parameters that are strictly ordered and typed, while also accepting an arbitrary number of "rest" parameters. The spread argument list of such a function evaluates as a variadic tuple type with a minimum fixed length, instead of a freely expandable (or contractable) array type.
`(...args: never[]) => unknown` covers functions for which all of the params can be typed together as a group e.g. `(...args: (string | number)[]) => T`, or it has a fixed number of params e.g. `(a: string, b: number) => T`. But to cover cases like `(a: string, b: number, ...rest: unknown[]) => T`, we need another top type with an even narrower type for the params: `(...args: never) => unknown`.
#### Avoid implicit, hard-coded generic parameters that are inaccessible from the outermost user-facing type.
* These are also called "return type-only generics" and are discouraged by the [Google TypeScript style guide](https://google.github.io/styleguide/tsguide.html#return-type-only-generics).
* Implicit generic parameters make it difficult to debug typing issues, and also makes the type brittle against future updates.
* Exception: If the intention is to encapsulate certain generic parameters as "private" fields, wrapping the type in another type that only exposes "public" generic parameters is a good approach.
## Further reading
* [Official Typescript documents of Do's and Don'ts](https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)

0 comments on commit c87162c

Please sign in to comment.