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.
- 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');