# टाइप गार्ड्स — टाइपस्क्रिप्ट

Source: https://www.geekswithgeeks.com/hi/typescript/ts-type-guards

> रनटाइम जाँच से किसी व्यापक टाइप को विशिष्ट टाइप तक संकरा करें।

## typeof से नैरोइंग

`if (typeof x === "string")` ब्लॉक के अंदर, TS जानता है कि उस ब्रांच में `x` एक `string` है।

```typescript
function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); // id is string here
  } else {
    console.log(id.toFixed(2));    // id is number here
  }
}
```

## instanceof से नैरोइंग

क्लासों के लिए, `instanceof`, क्लास टाइप्स के यूनियन को मेल खाने वाले तक संकरा करता है।

```typescript
class Cat { meow() { return "Meow!"; } }
class Dog { bark() { return "Woof!"; } }

function speak(pet: Cat | Dog) {
  if (pet instanceof Cat) {
    console.log(pet.meow());
  } else {
    console.log(pet.bark());
  }
}
```

## नैरो क्यों करें?

यूनियन टाइप केवल वे प्रॉपर्टीज़ दिखाता है जो **हर सदस्य में साझा** हैं। नैरोइंग कंपाइलर को साबित करती है कि असल में आपके पास कौन-सा सदस्य है, जिससे उसकी विशिष्ट प्रॉपर्टीज़ और मेथड्स खुल जाते हैं।

**Quiz:** `if (typeof id === "string") { ... }` के अंदर, TS `id` को कौन-सा टाइप देता है?

- [ ] string | number, अपरिवर्तित
- [x] string
- [ ] any

*Answer:* string. typeof जाँच उस ब्लॉक के अंदर यूनियन को केवल string तक संकरा कर देती है।
