Skip to content

Instantly share code, notes, and snippets.

@BrenoOPrado
Last active November 1, 2022 19:19
Show Gist options
  • Save BrenoOPrado/73e017b7ed910065bb3cb193bdc4604f to your computer and use it in GitHub Desktop.
Save BrenoOPrado/73e017b7ed910065bb3cb193bdc4604f to your computer and use it in GitHub Desktop.
Guia de typeScript

para treinar typeScript: https://www.typescriptlang.org/pt/play


Possiveis tipos:

primitive:

  • boolean
  • number
  • string
  • Date
  • enum
  • void
let yes: boolean;
const yes: boolean = true;

let x: number;
const y: number = 0;
const z: number = 123.456;

let s: string;
const empty: string = "";

let d: Date;
const firstTrybeDay: Date = new Date("2022-03-21")

function sayHelloWorld(): void {
  console.log('void para função sem retorno');
}

// ------------------------------------------------------------

export function greeter(name: string):string {
    // indica o tipo do parametro e o tipo de retorno esperado
    return `Olá ${name}!`;
}

object:

  • class
  • interface
  • array
  • tupla
  • literals
class Person {
    // informando os tipos das variaveis this.
    _name: string;
    _birthDate?: Date;
    _age: number;
    
    constructor(name: string, birthDate?: Date, age: number;) {
        // ? indica que não é obrigatório
        this._name  = name;
        this._birthDate  = birthDate;
        this._age  = age;
    }

    speak(): void {
        console.log(`${this.name} está falando.`);
    }
}

const person1 = new Person("Jane Doe", 27);

person1.speak();
// saída: "Jane Doe está falando."

person1.birthDate = new Date("1986-01-01");

// ------------------------------------------------------------

interface Employee {
    firstName: string;
    lastName: string;
    fullName(): string;
}

let employee: Employee = {
    firstName : "John",
    lastName: "Doe",
    fullName(): string {
        return this.firstName + " " + this.lastName;
    }
}

employee.firstName = 10;  // Error: Type "number" is not assignable to type "string"

// É possivel externder uma interface
interface Teacher extends Employee {
    subject: string;
    sayHello(): string;
}

let teacher: Teacher = {
    firstName: "John",
    lastName: "Doe",
    subject: "Matemática",
    fullName(): string {
        return this.firstName + " " + this.lastName;
    },
    sayHello(): string {
        return `Olá, eu sou ${this.fullName()} e leciono ${this.subject}`;
    }
}

// ------------------------------------------------------------



const arrayName: type[] = [....conteúdo do array....];
const names: string[] = ['nome1', 'nome2', 'nome3'...];

type Character = {
  nickname: string;
  stats: { agi: number, str: number, int: number, hp: number, mp: number };
  createdAt: Date;
};

const characters: Character[] = [
  {
    nickname: 'name1',
    stats: { agi: 50, str: 100, int: 25, hp: 1000, mp: 300 },
    createdAt: new Date('2003-10-1')
  },
  {
    nickname: 'name2',
    stats: { agi: 80, str: 40, int: 150, hp: 630, mp: 1100 },
    createdAt: new Date('2003-10-2')
  },
];

// ------------------------------------------------------------

const fullName = [string, string] = ['name', 'surname'];
const person: [string, number] = ['name', 20];

// ------------------------------------------------------------

console.log(`Texto ${variável}`);

  • null
  • undefined
const nullValue = null;
const undefinedValue = undefined;

  • para instalar typecript globalmente:
npm install -g typescript
  • para executar:
tsc nomeDoArquivo.ts
  ou
npx tsc nomeDoArquivo.ts
  • para rodar o arquivo gerado:
node nomeDoArquivo.js
  • para gerar o 'tsconfig.json':
// com o compilador instalado globalmente:
tsc --init

ou 

// caso o compilador não esteja instalado globalmente:
npx tsc --init

Type Aliases:

type Point = {
  x: number;
  y: number;
};


function printCoord(pt: Point) {
  console.log("O valor da cordenada x é: " + pt.x);
  console.log("O valor da coordenada y é: " + pt.y);
}

printCoord({ x: 100, y: 100 });
//saída:
//O valor da cordenada x é: 100
//O valor da cordenada y é: 100

Type Unions:

function imprimirCPF(cpf: number | string){
  console.log("Seu CPF é: " + cpf);
}

imprimirCPF(11111111111);
// Seu CPF é: 11111111111
imprimirCPF('111.111.111-11');
// Seu CPF é: 111.111.111-11

Type Assertion:

type User = {
  name: string,
  email: string,
  password: string,
}

function stringToJson(str: string): unknown {
  const result = JSON.parse(str);
  return result;
}

const user = stringToJson('{"name":"André Soares","email":"andre@trybe.com","password":"senha_secreta"}') as User;
 // ou
const user = <User> stringToJson('{"name":"André Soares","email":"andre@trybe.com","password":"senha_secreta"}');
 // ou
const user = stringToJson<User>('{"name":"André Soares","email":"andre@trybe.com","password":"senha_secreta"}');

// -----------------------------------------------------------------------------------

const str: unknown = 'texto'; // simulando um valor supostamente desconhecido

str.split(''); // Dispara um erro por aplicar um split em um tipo desconhecido
(str as string).split('') // Corrigindo o erro acima usando o 'as'

const num: string = '2';

num as number // dispara um erro, pois não é possível usar Type Assertions com tipos incompatíveis
(num as unknown) as number // Corrigindo o erro acima convertendo primeiramente para unknown

Generics:

function identity<T, U> (value: T, message: U) : T {
    console.log(message);
    return value
}

const returnNumber = identity<number, string>(100, "Olá");
const returnString = identity<string, string>("100", "Mundo");
const returnBoolean = identity<boolean, string>(true, "Olá, Mundo!");

Model em classe:

com MySQL:

import { Pool, RowDataPacket, ResultSetHeader } from "mysql2/promise";
import connection from "./connection";

export interface Book {
  id?: number,
  title: string,
  price: number,
  author: string,
  isbn: string,
}

export default class BookModel {
   private connection: Pool;

   constructor(){
     this.connection = connection;
   }
  
  // Exemplos de funções das models -------------------------------------------------------
  
   public async getAll(): Promise<Book[]> {
     const [rows] = await this.connection
       .execute<(Book & RowDataPacket)[]>('SELECT * FROM books');
    
     return rows;
   }
   
   // -------------------------------------------------------------------------------------
   
   public async create(book: Book): Promise<Book> {
    const { title, price, author, isbn } = book;

    const [{ insertId }] = await this.connection
      .execute<ResultSetHeader>(
        'INSERT INTO books (title, price, author, isbn) VALUES (?, ?, ?, ?)',
        [title, price, author, isbn],
    );

    return { id: insertId, ...book };
  }
}

com sequelize:

// model --------------------------

import { Model } from 'sequelize';
import db from '.';

class Books extends Model {
  declare id: number;
  declare title: string;
  declare author: string;
}

Books.init({
  id: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
  },
  title: {
    type: Sequelize.STRING(30),
    allowNull: false,
  },
  author: {
    type: Sequelize.STRING(100),
    allowNull: false,
  },
}, {
  sequelize: db,
  modelName: 'books',
  timestamps: false,
});

export default Books;

// uso da model --------------------------

import Books from "./database/models/BookModel"

(async () => {

  const books = await Books.findAll({ raw: true });
  console.table(books);
  process.exit(0);

})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment