## Notes
Narrow down the type within a conditional block using `typeof`.
```typescript
type alphanumeric = string | number;
function add(a: alphanumeric, b: alphanumeric) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
if (typeof a === 'string' && typeof b === 'string') {
return a.concat(b);
}
throw new Error('Invalid arguments. Both arguments must either be numbers or strings.');
}
```
## Using Instanceof
```typescript
class Customer {
isCreditAllowed(): boolean {
// ...
return true;
}
}
class Supplier {
isInShortList(): boolean {
// ...
return true;
}
}
type BusinessPartner = Customer | Supplier;
function signContract(partner: BusinessPartner): string {
let message: string
if (partner instanceof Customer) {
message = partner.isCreditAllowed()
? 'Sign a new contract with the customer'
: 'Credit issue';
}
if (partner instanceof Supplier) {
message = partner.isInShortList()
? 'Sign a new contract with the supplier'
: 'Need to evaluate further';
}
return message;
}
```
Can also use `if-else` if all cases are accounted for:
```typescript
function signContract(partner: BusinessPartner): string {
let message: string;
if (partner instanceof Customer) {
message = partner.isCreditAllowed()
? 'Sign a new contract with the customer'
: 'Credit issue';
} else {
message = partner.isInShortList()
? 'Sign a new contract with the supplier'
: 'Need to evaluate further';
}
return message;
}
```
## In
The `in` operator carries a safe check for the existence of a property on an object.
```typescript
function signContract(partner: BusinessPartner): string {
let message: string;
if ('isCreditAllowed' in partner) {
message = partner.isCreditAllowed()
? 'Sign a new contract with the customer'
: 'Credit issue';
} else {
message = partner.isInShortList()
? 'Sign a new contract with the supplier'
: 'Need to evaluate further';
}
}
```
## User-Defined Type Guard
```typescript
function isCustomer(partner: any): partner is Customer {
return partner instanceof Customer;
}
```
And then it can be used as
```typescript
function signContract(partner: BusinessPartner): string {
let message: string;
if (isCustomer(partner)) {
message = partner.isCreditAllowed()
? 'Sign a new contract with the customer'
: 'Credit issue';
} else {
message = partner.isInShortList()
? 'Sign a new contract with the supplier'
: 'Need to evaluate further';
}
}
```
## References
- [Type Guards - TypeScript Tutorial](https://www.typescripttutorial.net/typescript-tutorial/typescript-type-guards/)