## Notas
`type` is a keyword that defines the shape of data. `Type`s include
- String
- Boolean
- Number
- Array
- Tuple
- Enum
- Advanced Types
[[(ts) type alias]] means "a name for any type". They are a way of creating new names for existing types.
`type ErrorCode = number | string;`
## Interfaces
Defines a contract that an object must adhere to.
```typescript
interface Client {
name: string;
address: string;
}
type Client = {
name: string;
address: string;
}
```
## Differences
### Primitive Types
- number
- string
- boolean
- null
- undefined
```typescript
// type alias
type Address = string;
```
Interfaces can only be used for object types, not for single primitives.
### Union Types
`type Transpot = 'Bus' | 'Car' | 'Bike' | 'Walk';`
Can define a Union Type from multiple primitives. Can also define a Union Type from multiple interfaces.
```typescript
interface CarBattery {
power: number;
}
interface Engine {
type: string;
}
type HybridCar = Engine | Battery;
```
### Function Type
Function Type represents a function's signature
```typescript
type AddFn = (num1: number, num2: number) => number;
```
Can also use an interface
```typescript
interface IAdd {
(num1: number, num2: number): number;
}
```
Using `type` is shorter. `type` also has more features (conditional types, mapped types, etc).
```typescript
type Car = 'ICE' | 'EV';
type ChargeEV = (kws: number) => void;
type FillPetrol = (type: string, liters: number) => void;
type RefillHandler<A extends Car> = A extends 'ICE' ? FillPetrol : A extends 'EV' ? ChargeEV : never;
const chargeTesla: RefillHandler<'EV'> = (power) => {
// implementation
}
const refillToyota: RefillHandler<'ICE'> = (fuelType, amount) => {
// implementation
}
```
### Declaration Merging
Exclusive to interfaces. Define interface multiple times and the compiler will combine them together.
```typescript
type Client {
name: string;
}
type Client {
age: number;
}
const harry: Client = {
name: 'Harry',
age: 42
}
```
#### Use Case
When enhancing a third party library's type definitions.
### Extends Vs Intersection
```typescript
type VIPClient extends Client {
benefits: string[]
}
```
For types, we would need to use the `intersection` operator
```typescript
type VIPClient = Client & { benefits: string[] }
```
Can also extend a type using an interface
```typescript
type Client {
name: string;
}
interface VIPClient extends Client {
benefits: string[]
}
```
## Referencias
- [[TypeScript]]
- [Types vs Interfaces](https://blog.logrocket.com/types-vs-interfaces-typescript/ )