Add tech_docs/TypeScript.md

This commit is contained in:
2024-06-27 06:12:34 +00:00
parent e8be312dd3
commit a2dc749dbf

115
tech_docs/TypeScript.md Normal file
View File

@@ -0,0 +1,115 @@
The line `const next = queue.shift()!;` is written in TypeScript, and it does the following:
1. **`queue.shift()`**:
- `shift()` is a method on JavaScript arrays that removes the first element from the array and returns that element. This method mutates the array by removing the first element.
- If the array is empty, `shift()` returns `undefined`.
2. **`const next = ...;`**:
- This declares a constant variable named `next` and assigns it the value returned by `queue.shift()`.
3. **`!` (non-null assertion operator)**:
- The `!` operator is a TypeScript-specific operator known as the non-null assertion operator.
- It tells the TypeScript compiler that you are confident the value is not `null` or `undefined`.
- This is useful in cases where the TypeScript type checker might otherwise warn that a value could be `undefined`.
Putting it all together:
- `queue.shift()` removes the first element from `queue` and returns it.
- `const next = ...;` assigns the returned value to the constant `next`.
- The `!` operator is used to assert to TypeScript that `queue.shift()` will not return `undefined`.
### Example
Here's an example to illustrate how it works:
```typescript
let queue: number[] = [1, 2, 3, 4];
const next: number = queue.shift()!; // next will be 1, and queue will be [2, 3, 4]
console.log(next); // 1
console.log(queue); // [2, 3, 4]
```
In this example:
- `queue` starts with the elements `[1, 2, 3, 4]`.
- `queue.shift()` removes the first element (1) and returns it.
- The `!` operator asserts that `queue.shift()` is not `undefined`, so `next` is assigned the value `1`.
- The array `queue` is now `[2, 3, 4]`.
### Important Note
Using the non-null assertion operator `!` should be done with caution. If there's a possibility that `queue` could be empty when `shift()` is called, it might lead to runtime errors. Always ensure that the array is not empty before using this pattern, or handle the potential `undefined` case properly.
---
Non-null assertions are used in TypeScript to inform the compiler that a certain value or expression will not be `null` or `undefined` at runtime, even if the type system cannot guarantee it. This can be particularly useful in a few scenarios:
1. **Definite Assignment**:
- When you have a variable that you know will be assigned a non-null value before it is used, but the TypeScript compiler cannot infer this. For example, when using variables that are initialized later or in a more complex control flow.
2. **DOM Manipulation**:
- When working with DOM elements where you know that an element exists but the TypeScript type system cannot confirm it (e.g., using `document.getElementById`).
3. **Event Listeners**:
- When handling events and you are certain that certain properties will be present.
4. **Type Guards**:
- After performing type checks or type guards, to assert that a variable is definitely non-null or non-undefined.
5. **Complex Data Structures**:
- When dealing with nested structures or APIs where you know the structure is non-null after certain operations or conditions.
### Examples
#### Definite Assignment
```typescript
let value!: number;
initializeValue();
console.log(value);
function initializeValue() {
value = 42;
}
```
Here, `value!` tells TypeScript that `value` will definitely be assigned before it is used, even though the assignment is not immediately obvious to the compiler.
#### DOM Manipulation
```typescript
const element = document.getElementById('myElement')!;
element.style.backgroundColor = 'blue';
```
In this example, the `!` asserts that `document.getElementById('myElement')` will not return `null`.
#### Event Listeners
```typescript
document.addEventListener('click', (event) => {
const target = event.target as HTMLElement;
const id = target.id!;
console.log(id);
});
```
Here, `target.id!` asserts that `id` is not `null` or `undefined`, assuming you know the clicked element will always have an `id`.
#### Type Guards
```typescript
function printLength(value: string | null) {
if (value !== null) {
console.log(value.length);
}
}
```
After the check `if (value !== null)`, you can use `value!` to assert that `value` is not `null`.
### Cautions
- **Runtime Errors**: Misusing non-null assertions can lead to runtime errors if the value is actually `null` or `undefined`.
- **Type Safety**: Overusing non-null assertions can undermine the type safety that TypeScript provides.
Using non-null assertions should be a well-considered decision based on a thorough understanding of the code and its flow to ensure that the assertions are accurate.