Skip to content

Commit f130035

Browse files
committed
WIP: Unions
1 parent 4a7919b commit f130035

File tree

3 files changed

+88
-3
lines changed

3 files changed

+88
-3
lines changed

README.md

+50-3
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ function greet(name: string, years: number) {
472472
greet("Galadriel", 5600);
473473
```
474474

475-
### Type annotation no retorno
475+
#### Type annotation no retorno
476476

477477
```typescript
478478
function getFavoriteNumber(): number {
@@ -482,7 +482,7 @@ function getFavoriteNumber(): number {
482482

483483
Os type annotations em retorno são menos comuns, assim como a tipagem de variável. O TS também costuma inferir essas informações.
484484

485-
#### Funções que retornam Promises
485+
##### Funções que retornam Promises
486486

487487
Se a sua função retorna uma Promise, assinale o tipo Promise no retorno.
488488

@@ -492,7 +492,7 @@ async function fetchNumber(): Promise<number> {
492492
}
493493
```
494494

495-
### Funções anônimas
495+
#### Funções anônimas
496496

497497
O TS vai tentar inferir os tipos nas funções anônimas.
498498

@@ -514,6 +514,53 @@ names.forEach((name) => {
514514

515515
Logo após os tipos primitivos, são os tipos com os quais mais se lida ao usar TypeScript, pois eles correspondem a qualquer valor em JS que possua propriedade.
516516

517+
```typescript
518+
function printCoord(point: { x: number; y: number }) {
519+
console.log(`The coordinate's x value is ${point.x}.`);
520+
console.log(`The coordinate's r value is ${point.y}.`);
521+
}
522+
523+
const route = {
524+
x: 42,
525+
y: 23,
526+
};
527+
528+
printCoord(route);
529+
```
530+
531+
### Propriedades opcionais (`?`)
532+
533+
**OBS.: para especificar um tipo opcional, use `?`.**
534+
535+
```typescript
536+
function getProfile(name: string, religion?: string) {
537+
if (religion && religion.length > 1) {
538+
return console.log(`My name is ${name} and my religion is ${religion}`);
539+
}
540+
541+
return console.log(`My name is ${name} and perhaps I am an atheist.`);
542+
}
543+
544+
getProfile("Tolkien", "Christianism");
545+
getProfile("Richard Dawkins");
546+
```
547+
548+
**OBS.: Em TS, ao usar um parâmetro opcional, primeiro cheque se ele é `undefined`.**
549+
550+
## Union Types
551+
552+
A definição de Unions é combinação de tipos. Então, se você cria um tipo formado por dois ou mais tipos, você tem um Union. Eles representam valores que podem ser de qualquer um desses tipos. Os tipos pertencentes a Unions são chamados de _membros_.
553+
554+
### Definição vagamente matemática
555+
556+
Eu entendo os Unions num sentido vagamente matemático. União como uma união/intersecção de determinado conjunto mesmo. Se uma função, por exemplo, aceita um parâmetro que pode ser tanto `string` quanto `number`, é porque o tipo esperado dela encontra-se justamente na intersecção entre strings e números.
557+
558+
Essa noção é vaga porque eu não sou matemático. Se essa minha definição fizer sentido, nem que seja mnemônico, vou adotá-la. Se não fizer sentido nenhum, eu apago e tento fixar o conceito de outra forma.
559+
560+
### Trabalhando com Unions
561+
562+
Seguindo essa definição, o TypeScript só permite uma operação que for comum a todos os membros do union. Portanto, se um union type conter `string | number`, você não pode chamar um `.length` ou um `.toUpperCase()` nele, por exemplo.
563+
517564
# Projetos de exemplo neste repositório
518565

519566
- [TypeScript Sample Project](https://github.com/divertimentos/typescript-learning/tree/main/example-projects/typescript-sample)

example-snippets/objects.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
console.clear();
2+
3+
function printCoord(point: { x: number; y: number }) {
4+
console.log(`The coordinate's x value is ${point.x}.`);
5+
console.log(`The coordinate's r value is ${point.y}.`);
6+
}
7+
8+
const route = {
9+
x: 42,
10+
y: 23,
11+
};
12+
13+
// printCoord(route);
14+
15+
function getProfile(name: string, religion?: string) {
16+
if (religion && religion.length > 1) {
17+
return console.log(`My name is ${name} and my religion is ${religion}`);
18+
}
19+
20+
return console.log(`My name is ${name} and perhaps I am an atheist.`);
21+
}
22+
23+
// getProfile("Tolkien", "Christianism");
24+
// getProfile("Richard Dawkins");

example-snippets/unions.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
console.clear();
2+
3+
function printId(id: number | string) {
4+
console.log(`This is your identification: ${id} (type: ${typeof id}).`);
5+
}
6+
7+
// printId("Comitê Revolucionário Ultrajovem");
8+
// printId(42);
9+
10+
function unionsRestrictions(name: string | number) {
11+
return name.length;
12+
}
13+
14+
unionsRestrictions("Lúthien Tinúviel");

0 commit comments

Comments
 (0)