DEV Community

Joao Carlos Sousa do Vale
Joao Carlos Sousa do Vale

Posted on

Leaning TypeScript

My annotations about TypeScript.

Commands:

  • initialize a npm empty package (package.json)
npm init -y

Wrote to C:\TypeScript\package.json:

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode
  • install typescript
npm install --save-dev typescript
or
npm i -D typescript

added 1 package, and audited 2 packages in 3s

found 0 vulnerabilities
Enter fullscreen mode Exit fullscreen mode
  • typescript configuration
npx tsc --init

Created a new tsconfig.json with:
                                                                                                         TS
  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true


You can learn more at https://aka.ms/tsconfig.json
Enter fullscreen mode Exit fullscreen mode
  • compile ts
npx tsc
Enter fullscreen mode Exit fullscreen mode
  • modify your package.json to compile using npm:
    • add "build"
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc"
Enter fullscreen mode Exit fullscreen mode
npm run build
Enter fullscreen mode Exit fullscreen mode
  • uses tsconfig.json to modify the project configurations like:
    • "rootDir": "./src"
    • "outDir": "./build"
    • "noEmitOnError": true

Data Types

string

let nome: string;

nome = 'João';

function nomeCompleto(nome: string, sobrenome: string) {
  return nome + ' ' + sobrenome;
}

nomeCompleto('João', 'Silva');
Enter fullscreen mode Exit fullscreen mode

number

let idade: number;

idade = 25;

function somar(a: number, b: number) {
    return a + b;
}

somar(1,1);
somar(2,4);
Enter fullscreen mode Exit fullscreen mode

boolean

let active: boolean;

active = true;

function verificarAtivo(ativo: boolean) {
    if (active) {
        return 'Ativo';
    } else {
        return 'Inativo';
    }
}

verificarAtivo(false);
Enter fullscreen mode Exit fullscreen mode

array

const nomes: string[] = ['João', 'Maria', 'Pedro'];

function printNames(nomes: string[]) {
  return `nomes: ${nomes.join(', ')}`;
}

console.log(printNames(nomes));
Enter fullscreen mode Exit fullscreen mode

tuple

const pessoas: [string, string, string] = ['João', 'Maria', 'Pedro'];

const joao: [string, number] = ['João', 25];

const maria: [string, number] = ['Maria', 20];
Enter fullscreen mode Exit fullscreen mode

enum

enum Profiles{
    admin,
    editor, 
    user
}

enum Cores {
  red = '\u001b[31m',
  black = '\u001b[30m',
}

const usuario = {
    level: Profiles.admin
}

console.log(usuario);
Enter fullscreen mode Exit fullscreen mode

type alias

type User = {
  name : string;
  lastName: string;
  birthday: string;
  age?: number;  //optional
}

const user: User = {
  name: 'some name',
  lastName: 'some last name',
  birthday: '01/01/1900',
}
Enter fullscreen mode Exit fullscreen mode

union type

type LogLevel = 'info' | 'error' | 'debug'

function logMessage(message: string, level: LogLevel) {
  console.log(`[${level}] - ${message}`)
}

logMessage("A message", 'info')
Enter fullscreen mode Exit fullscreen mode

intersection types

type About = {
  bio: string;
  interests: string[];
}

type Profile = User & About;
const userWithProfile: Profile = {
  name: 'name',
  lastName: 'lastname',
  birthday: '01/01/1900',
  bio: 'bio',
  interests: ['games', 'sports'],
}
Enter fullscreen mode Exit fullscreen mode

other types

  • any
    • type not defined;
let value: any;

value = 25;
value = '25';
Enter fullscreen mode Exit fullscreen mode
  • unknown
    • type any + validations.
let informations: unknown;
let completeInformations: string;

completeInformations = informations; //don't compile, with any compile
Enter fullscreen mode Exit fullscreen mode
  • undefined

    • instances without values;
  • null

  • object

  • void

  • never, used in functions:

    • error return;
    • infinite loops;

Objects

class User {

  public name;
  public idade;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

//inheritance
class Player extends User {

  public game;

  constructor(name: string, age: number, game: string) {
    super(name, age);
    this.game = game;
  }

  currentGame() {
    return `I am playing ${this.game}`; 
  }

  static currentTime() {
    return Date();
  }
}

const user = new User("name", 15)
console.log(user)

const player = new Player("name", 18, "game");
console.log(player.currentGame());

//static
console.log(Player.currentTime());
Enter fullscreen mode Exit fullscreen mode

private x protected

class Game {
  private name;
  protected otherName;

  constructor(name: string, otherName: string) {
    this.name = name;
    this.otherName = otherName;
  }

  getName() {
    return name;
  }
}

class SpecialGame extends Game {
  private description;

  constructor(name: string, description: string) {
    super(name, "other");
    this.description = description;
  }

  getOtherName() {
    return this.otherName;
  }
}
Enter fullscreen mode Exit fullscreen mode

interface

interface IGame {
  getDescription(): string;
}

class Game implements IGame {

  getDescription(): string {
    return "";
  }
}

const objeto: IGame = {
  getDescription(): string {
    return "something";
  }
}
Enter fullscreen mode Exit fullscreen mode

References:
Typescript Lang

Discussion (1)

Collapse
andrewbaisden profile image
Andrew Baisden

Keep up the good learning!