Skip to content

Instantly share code, notes, and snippets.

@brauliodiez
Last active June 4, 2017 09:17
Show Gist options
  • Save brauliodiez/b46971bf44acb15a084c7c439c2a3afc to your computer and use it in GitHub Desktop.
Save brauliodiez/b46971bf44acb15a084c7c439c2a3afc to your computer and use it in GitHub Desktop.
Typescript, playing a bit with types

Start

For sure now you will have a lot of questions poping up into your head, about cases where typing has not to be strict.

We will continue using typescript playground.

Let's start diving into that.

Topics to cover:

  • any
  • casting
  • multiple types
  • Function types.
  • Default values on params.

Steps

  • What happens if I really need to store in that variable things that can be of any type? We can use the 'any' type...
let a : number = 3;
let b : any = 5;

b= "5";

const result = a + b;

console.log(result);

No error messages now, any means whatever type, now we get no error messages but the 35 result.

  • That's nice, but what if I need to convert from e.g. string to number?
const myString = "3";

// Approach 1, parseInt
const myNumberA = parseInt(myString);

// Approach 2, '+'
const myNumberB = +myString;

console.log(myNumberA);
console.log(myNumberB);
  • But what happens if my var can hold two possible types? Let's say a number and a string? Should I have to use any? or can I define both types?
let myThing : (string | number) = 3;

console.log(myThing);

myThing = "Look ma! now I'm a string";

console.log(myThing);
  • One more before jumping into the next samples, I want to hold in a var a function.
const myWarningLogger = (message : string) => {
  console.warn(`Warning: ${message}`);
}

function sum(a, b, logger : (m : string) => void) {
  if(!a || !b) {
    logger('At least one of the entry params is null');
  }

  return a + b;
}

const a = 2;
const b = null;


sum(a, b, myWarningLogger);
  • What happens if we want to setup a default value for a given param on a function? Let's give a try
const bookingConfirmed = (info : string, additionalRequests : string  = '') => {
  console.log(`*********************************`);
  console.log(`Booking information: ${info}`);
  console.log(`Additional requests: ${additionalRequests}`);  
  console.log(`*********************************`);
} 

bookingConfirmed('Standard double room');
bookingConfirmed('Standard double room', 'extra bed');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment