TypeScript basics Revision 3: Use of Typeof #typescript #typeof #typescripttutorial #kamran #piaic

preview_player
Показать описание
In TypeScript, the `typeof` operator is often used to perform type introspection. It allows you to check the type of a value or variable at runtime and use that information to make decisions or enforce type constraints. Here are some real-life examples of how `typeof` can be used in TypeScript:

1. **Type Guards:**
You can use `typeof` in conjunction with conditional statements to create type guards, which help narrow down the type of a variable within a certain code block.

```typescript
function printMessage(message: string | number) {
if (typeof message === "string") {
} else {
}
}
```

In this example, `typeof message === "string"` is a type guard that allows you to safely call `toUpperCase` on `message` if it's a string and `toFixed` if it's a number.

2. **Runtime Type Checking:**
You can use `typeof` to perform runtime type checks and handle values differently based on their types.

```typescript
function processValue(value: any) {
if (typeof value === "string") {
// Handle string
} else if (typeof value === "number") {
// Handle number
} else {
// Handle other types
}
}
```

Here, `typeof` is used to check the type of `value` and execute different code blocks accordingly.

3. **Type Inference for Object Properties:**
`typeof` can be used to infer the types of object properties dynamically.

```typescript
function getProperty(obj: any, key: string) {
if (typeof obj[key] !== "undefined") {
return obj[key];
} else {
return "Property not found";
}
}
```

This function checks if a property with the given `key` exists on the `obj` and returns its value. It uses `typeof` to ensure type safety.

4. **Dynamic Key Generation:**
You can use `typeof` to dynamically generate keys based on the types of variables.

```typescript
function generateKey(obj: any, value: any) {
const key = typeof value === "string" ? `str_${value}` : `num_${value}`;
obj[key] = value;
}

const data = {};
```

Here, the `generateKey` function uses `typeof` to determine whether to prefix the key with "str_" or "num_" based on the type of `value`.

5. **JSON Serialization:**
When serializing objects to JSON, you can use `typeof` to conditionally include or exclude properties based on their types.

```typescript
function filterAndSerialize(obj: any) {
const filteredObj = {} as any;
for (const key in obj) {
if (typeof obj[key] !== "function") {
filteredObj[key] = obj[key];
}
}
return JSON.stringify(filteredObj);
}
```

In this example, the function filters out properties that are functions from the object before serializing it to JSON.

These examples demonstrate how the `typeof` operator can be used to perform runtime type checks, dynamically generate keys, and make decisions based on the types of values in TypeScript. However, it's important to note that `typeof` has limitations, and for more advanced type manipulation and checking, you might want to explore other TypeScript features like type guards, user-defined type predicates, and conditional types.

#TypeScript #TypeofOperator #TypeScriptTutorials #RuntimeTypeChecking #TypeScriptExamples #DynamicTyping
Рекомендации по теме
join shbcf.ru