Last active
September 1, 2021 22:24
-
-
Save Borzilov/c8e7bfcc164f27a0f092b8e83f38a45c to your computer and use it in GitHub Desktop.
Types for knowledge sharing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// BASIC | |
const language: string = 'JavaScript'; | |
const age: number = '33'; // Error | |
const amount = 55; | |
const price = '5'; | |
const discount = false; | |
const total = price * amount; // Error | |
price - discount; // Error | |
// Reassigning | |
let skills: string; | |
skills = 'JavaScript'; | |
skills = 'Java'; | |
skills = true; // Error | |
// Literal types | |
let attempts: 3 = 3; | |
attempts = 4; // Error | |
attempts = null; // depends on compilator configuration | |
let fruit: string; | |
let bananaFruit: 'banana' = 'banana'; | |
fruit = bananaFruit; // Ok | |
bananaFruit = fruit; // Error | |
//any + unknown | |
let animal: unknown; | |
animal = 'Dog'; | |
animal = 5; | |
animal.toString(); // Error | |
// Functions | |
function getAge(name: string): number { | |
// ...... | |
return Math.ceil(Math.random() * 100); | |
} | |
function getDrakulaAge(): never { | |
throw Error(`Drakula age couldn't be defined`); | |
} | |
function setAge(name: string, age: number): void { | |
} | |
function isAdult(age: number): boolean { | |
return age >= 18; | |
} | |
isAdult(getAge('USER_NAME')); | |
isAdult(getDrakulaAge()); | |
isAdult(setAge('Drakula', 20)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment