Check out this sentence:
Me am eating spaghetti š
You can probably easily identify that the sentence isĀ wrong. And you might even know enough English grammar to explain why.
If not, the short version is that the rules of English grammar create places in sentences forĀ subjectsĀ and places forĀ objects. āMeā is grammatically anĀ objectĀ while āIā is grammatically aĀ subject. So the problem is that weāve put anĀ objectĀ into a place whereĀ subjectsĀ are supposed to go in the sentence.
Even with this mistake, our brains are smart enough to figure out what meaning the sentence is conveying. Unfortunately, the TypeScript compiler is not quite as clever, which means we have to be careful about our code or risk spending another day battling Red Squiggly Lines of Doom.
Statements and Expressions in JavaScript
Programming languages also have underlying grammatical rules. And if youāve written even a small amount of JavaScript, youāve probably internalised some JavaScript grammar without realising.
For example, can you see whatās wrong with this code?
const flag = isEnabled && !isError() || const result = fetchResult(); // ā
If you āspeakā JavaScript, you probably intuitively recognise that something is wrong here, just as you probably intuitively recognised the incorrect sentence above.
Even the mistake here is roughly similar to āmeā versus āIā in English. In this case, weāve put aĀ statementĀ where only anĀ expressionĀ can go.
JavaScript Statements vs Expressions
Statement: A unit of code which provides a whole instruction.Ā
Expression: A bit of code which resolves to a value.
Some people find it easier to think of these as āstatements are things you can correctly wrap in curly braces, while expressions are things you can correctly wrap in parenthesesā.
For example: { const result = fetchResult(); /* this is a statementĀ / } ( isEnabled && !isError ) /Ā this is an expression */
Of course, the grammar of JavaScript is more complex than just these two elements. But understandingāeven without being able to explain!āthe difference betweenĀ statementsĀ andĀ expressionsĀ is a skill that JavaScript developers tend to pick up quite quickly.
š Notice also thatĀ expressionsĀ can combine together to create more complex expressions.
Both isEnabled and !isError() are themselves simple expressions. We can combine them together using operators such as && to create the expression isEnabled && !isError
Enter TypeScript
Along withĀ statementsĀ andĀ expressions, TypeScript adds an extra kind of thing that can appear in our ācode sentencesā. Unsurprisingly, this new thing is calledĀ types and is essential building block of beginner TypeScript.
Now we can open up places in our code where we can add aĀ type:
const result : /* š«µ TYPE GOES HERE š«µ */ = fetchResult();
Or:
function computeTotalCost(products : /* š«µ TYPE GOES HERE š«µ */)
{ /* function definition */ }
Weāre opening up a spot in the code where only a type can go by using the colon (:) operator. There are a couple of other ways to open up theseĀ type-places, such as the satisfies operator, but the colon is by far the most common.
These type-places are like a parallel universeāthe Land of Typesāliving in our code. A place where the only thing that is understood is types. If we want to refer to something from the Land of JavaScript, we have to convert it into a type, somehow. For example:
const someVariable = getData();
const result : someVariable /* ā NOT A TYPE */;
const result : typeof someVariable /* ā
WE CONVERTED IT TO A TYPE! */;
The basic rule is that whenever weāre visiting the Land of Types, we can put anything into thatĀ type-placeā¦Ā as long as itās a valid type.
š It could be a simple type, like string or Array.
š Or it could be a type weāve defined elsewhere, like Product or User, or one based on the typeof some variable.
š It could be an object, like { name: string; email: string; postCount: number; }
š Orālike how expressions can combine to create other expressionsāit could be a complex type that combines other types, like Product | Error | undefined
š”Defining Things in the Land of Types
This helps to make sense of the type and interface keywords. Just like the colon operator, whenever you use one of these keywords youāre visiting the Land of Types.
Think of these two as the Land of Types equivalent to let and const: Just as let and const defineĀ variablesĀ in the Land of JavaScript, type and interface define types in the Land of Types.
ā ļø OPINION ALERT ā ļø
When practicing beginner TypeScript, people often worry about type versus interface. Which should you use?!
With let/const thereās a clear winner: CONSTantly use const, LET yourself use let.
But the differences between type and interface are comparatively minor. When starting out, itās easier not to worry too much. Pick one and stick with it, or mix-and-matchāitās up to you! Once youāve got more comfortable with TypeScript, you can come back and understand those small differences.
š” If youāre really struggling to choose, theĀ TypeScript playground recommends you use āinterfaceāĀ to get slightly easier-to-read error messages in some cases.
š¤ Why does this matter?
TypeScript programming is all aboutĀ declaring your assumptions about whatās happening at that point in the code.
By opening up theseĀ type-placesĀ in your code, youāre effectively telling TypeScript: āHey, when I reach this line, I should have an Array of Users – can you make sure that thatās always true?ā If TypeScript then spots a way for you to reach that line of code where that assumption ISNāT true – for example, perhaps the data could be undefined – then it will show you an error.
TypeScript errors are famously hard to read, but theyāre mostly telling you about these sorts of contradictions: āYouāre calling this function with data that might be undefined, but you told me already that that function MUST have this data. Can you resolve that contradiction please?ā
Becoming a good TypeScript programmer is all about finding the neatest way to encode your assumptions into thoseĀ type-placesĀ in your code, which enables TypeScript to help you to keep your code bug-free! šŖ
Fancy refreshing your JavaScript skills and diving into some beginner TypeScript? We have just the programme if you’re looking to return to tech after a career break. Visit our programme page to learn more!