If you are familiar with JavaScript, then you are probably familiar with the surplus of small errors that come while coding it.
What if I were to tell you there was a way to code and avoid many of these errors? If you are unfamiliar with TypeScript you would most likely think I was lying.
TypeScript is the older brother of JavaScript, and as its name implies; there are types present within the language. Being the oddball mature younger brother the language is stricter than its sibling JavaScript.
To start a type can be declared as any with the any flag.
let anyType: any = 23
Unfortunately, this defeats the point of TypeScript as there is no real check.
A better use of TypeScript would be to declare a type like so:
let numberType: number = 23
This would force a type of number onto our variable and would not allow the variable to be redeclared. While this seems trivial declaring types can be done for every single JavaScript data type.
This would allow for function parameters and return values to be declared. For example:
function exponentiate(x: number, y: number) : string {
return Math.pow(x, y).toString();
}
In this instance we declared our parameters both as numbers and our return value as a string.
By having to do this pre-emptively, many mistakes are avoided due to fully thinking our function out and not writing spaghetti code.
The last piece of TypeScript I want to talk about are interfaces.
An interface allows for object class types to be created.
It also prevents objects from having incorrect data being passed in.
interface Person {
first: string;
last: string;
[key: string]: any
}
Notice the difference in the syntax compared to an object.
This would force an object with a Person interface to be forced to have a first and last name with string.
Utilizing the interface for an object would look like this:
const person: Person = {
first: "Hunt",
last: "Navar",
fast: true
}
This allows for first and last names to be forced but the fast parameter is optional!
I hope you learned something about JavaScript's brother. Use your new found powers for good!
Thanks for reading!
Top comments (4)
Typescript is not JS older brother, it was made after it as it is a superset of JavaScript
It's more of a
more mature younger brother
You are thinking too literally and didnt understand my analogy!
you didnt get my analogy!