
27.02.2022
typescript
Most people including me asks this question - do i really need TS ?!
If you buidling a simple Todo app, the short answer is No!
If the app is a little more complex, my personal opinion is: typescript is King!
The follow up question is "WHY?!"
It helps you think of some situations where your code will break.
Simple example:
1const elem = document.getElementByid('id'); 2const value = elem.value 3 4//for javascript its completly normal code, but not for TS 5//problm 1: elem is maybe null 6//problem 2: property value does not exist on all HTML elements 7 8const elem = document.getElementById('id') as HTMLInputElement | null; 9if (elem) { 10 const value = elem.value; 11} 12//Now we know what we can expect fom "elem" and how we can handle different scenarios
Using interfaces and types gives you batter understanding of what type of complex objects you work with, while you easily avoid property misspelling
1interface Person { 2 firstName: string; 3 lastName: string; 4 city: string; 5} 6const personOne = { 7firstName: 'Hristo', 8lastName: 'Manov', 9city: 'Sliven' 10 } as Person 11 12personOne.town 13//Property 'town' does not exist on type 'Person'.ts(2339) 14//Tip when you type personOne. and pres ctrl/command + space in VSC gives you all properties available for this object.
What is generics ?! They give you ability to create reusable functions, classes and code components, that work with multiple types instead of one.
1const person = { 2 firstName: 'Hristo', 3 lastName: 'Manov', 4 city: 'Sliven', 5}; 6 7const cat = { 8 name: 'Pijo', 9 breed: 'mixed', 10 age: '3 months' 11} 12function getProperty<T, K extends keyof T>(obj: T, key: K) { 13 return obj[key]; 14} 15 16//what keyof does is to create union type of all public properties names 17//simple union type = type SimpleUnionType = 'firstName' | 'lastName' | 'city'; 18//so why we dont use simple union type - beacuse as this way the function will work only for person and not for cat 19//using generic type gives the ability to work for both 20 21 22getProperty(person, 'town'); //Argument of type '"town"' is not assignable to parameter of type '"firstName" | "lastName" | "city"'. 23getProperty(person, 'city'); // OK 24 25getProperty(cat, 'town'); // Argument of type '"town"' is not assignable to parameter of type '"name" | "breed" | "age"'. 26getProperty(cat, 'name'); // Ok 27
Typescript is very powerfull tool for creating robust and flexible applications, its a good tradeof for the little extra code we need to write.