Beginner TypeScript: Statements, Expressions & Types

Typescript code on a laptop

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!

A button that says 'Check out our JavaScript & TypeScript programme!'

Sharing is caring
Previous article All Articles Next article
fwc shapes

Weā€™d love to hear from you!

If this blog has got you thinking or asking questions - we'd love to hear from you. Get in touch with our friendly team today and let's start making change together!

hexagon group white shadow
hexagon group white shadow