Use of Mapping Types in TypeScript

I’ve been reading up on my #Typescript and one feature that is under used is mapping types and using them to create new types. 

On some codebases I’ve worked on I’ve seen, and have been guilty of myself, creating new type definitions that maybe extend another Type or are extremely close. For example, a User type and a Staff type both have similar properties (firstname, lastname, email, id etc)

type User = { id,firstname, lastname, email};
type Staff = {id, firstname, lastname, email, jobtitle);

In the need to get a new feature completed it can be quiet easy to create a new Type definition without checking to see if there is something that is already within the code that can be used or extended. Creating new types as we go can lead to cases like above where two types have been created, the original User type and the quickly written Staff type that is needed in a function of a component I’m developing as part of that feature that needs to be done, and I know that I will go back and refactor the code to use an extended or mapped type when I have time (which we all know, we never do).

This is where I feel in my own code mapping types should be used. With a mapping I can create my new type, and if for some reason (API changes or another developer changes the original definition) the remapping of my new type is updated if the original type is changed. So in the case of our User and Staff types if there is a change to the API and title is added as a property which needs to also be displayed in a screen that is making use of the Staff type. By using a Mapped type, this new property is automatically available.

I feel this makes the code more robust and flexible to change, the issue with mapping types is that the syntax is not as clear as using the extends keyword, but really all we are doing in a mapped type is looping over another key and picking what we want from it to create a new type and if that original type changes our derived mapped type can be amended too without to much work.

I think the main aim for how I should write my TypeScript code is to think what are the main data structures in an app, maybe defined by what an API is returning me or what I’m asking for if using GraphQL, and how can set up all the other Types in my application to be created or inferred from these base Types. So my code is both type safe but also flexible enough to handle changes over time. (I think this is the main message Matt Pocock has been trying to get across in his courses and book).

React logo
Notes on NextJS: Routing in NextJS

Over the last few weeks, I’ve been delving deeper into Next.js, the React meta-framework. One of the initial hurdles when acquainting oneself with a new framework is understanding its routing mechanism, a fundamental feature of any web application.

Next.js takes a unique folder-based approach, distinguishing itself from other frameworks I’ve worked with. Unlike Angular and Vue, which utilise a component-based router system detached from the application’s source folder structure, Next.js integrates routing seamlessly into its architecture, building upon React’s inherent lack of a default routing system. It’s fascinating to observe how Vercel has seamlessly integrated this functionality into the Next.js framework.

The folder-based routing system in Next.js is remarkably straightforward. Each route within your application corresponds to a sub-folder in your source directory, with each sub-folder containing a page.tsx file representing the destination of that route.

While this approach is innovative, it’s not entirely novel. In the early days of web development, before the advent of JavaScript frameworks and server-side rendering, we employed a similar folder-based routing system, where each route corresponded to an index.html file within its respective folder. For example, the homepage’s route would be http://www.mysite.com/index.html, while a separate route would be http://www.mysite.com/news/index.html. This historical perspective underscores the cyclical nature of ideas in the web industry.

It’s heartening to witness the simplification of routing, particularly with Next.js’s support for dynamic routes. Moreover, it’s intriguing to note that other frameworks, such as Nuxt for Vue and AngularJS for Angular, are also adopting folder-based approaches. This resurgence of an old concept underscores the enduring nature of certain ideas within the ever-evolving landscape of web development.

Demo app

https://github.com/Stephenradams/star-wars-search

To learn a bit about the routing and how to call external APIs in Next I created a small demo app using the Star Wars API to get lists of Films, People and Planets. Its a very simple app, but these small demo apps are a great way of learning new concepts.

In this demo app you can see that the folder structure uses a folder for each sub-section (films, planets, species, starships):

Inside each folder is a page.tsx file which is the ‘homepage’ of the route, these sub-folders can also have a layout.tsx file which defines the layout of the page, by overriding the main layout.tsx layout.

To support dynamic routes, NextJS uses a special sub-folder named [id] where the dynamic property, in this case an id number used to direct the user to another page.tsx file inside this special sub-folder:

This dynamic parameter is accessible within the page.tsx file via the component params:

export default async function Page({ params }: { params: { id: string } }) {
    const filmId = params.id;
    const filmDetails: FilmDetails = await getFilm(params.id);
    console.log(filmDetails.title);

So in this example code I’m getting the ID from the params and then passing it to my API call. It’s so simple and straight forward, I’m not adding anything to a routes file, or setting up routes and getting the URL params is extremely easy.

I really like the approach Next has taken with routing, now I’m going to take a look at handling forms and form data which is another common function of web apps.

NextJS, a new journey

Over the past few weeks, I’ve been diving into #NextJS and #React for a couple of reasons. Firstly, I’m a firm believer in continually learning new things, whether it’s a different framework or a fresh language. Plus, let’s face it, React is a big deal in the business of frontend development. As a freelancer or contractor, having some React know-how opens up a wider range of projects to dive into.

My initial impression of React is pretty positive. It’s a lightweight library that’s perfect for whipping up frontend apps, especially ones that need to hook into hefty APIs like those powered by Node.js or .NET. If your team is all about the frontend/UI side of things, React is definitely worth considering.

Comparing it to Angular, React is a whole different beast. It doesn’t come packed with all the bells and whistles Angular does out of the box (think routing, testing, RxJS, Services, etc.). But hey, Angular’s been making strides to simplify things lately, which is great news for its future.

Now, onto NextJS. It’s like the Swiss Army knife of application frameworks. It gives you all the tools you need to build a top-notch app right out of the gate. I’ll admit, the concept of Server components and Client components threw me off a bit coming from an Angular background. But hey, in NextJS, everything’s a Server component unless you say otherwise. Plus, having server-side rendering baked in is a nice touch.

I’m also digging NextJS’s App Router and file-based routing. Compared to Angular’s routing, it’s way more straightforward. Sure, other frameworks like AnalogJS are jumping on the file-based routing train too, but I haven’t gotten my hands dirty with AnalogJS just yet.

So, my plan? Stick with NextJS and see where it takes me. I’ll be putting my name out there for contracts and projects that are NextJS-friendly.

One thing I firmly believe is that no matter which framework you’re into, a good web developer can adapt to any of the big ones out there (Angular, React, Vue). It’s not just about how many years you’ve racked up using a framework—it’s about being a team player, understanding what the client needs, communicating effectively, staying open to learning from others, and bouncing ideas around.

Anyway, I’m excited to see where this NextJS journey leads me!

Angular’s new component structure

With all the new features coming in Angular, the structure of the component (which are the building blocks of an Angular app) is, in my opinion, changing from what it use to be.

Before the introduction of standalone components and Signals, a typical Angular component would be made up of:

  • A TypeScript file
  • A HTML template
  • A CSS/SCSS file

Each part of the component, nicely separated in it’s own file and each component belonging to it’s own module. This approach has worked for many projects and is still used in a lot of Angular projects. It’s great, but things have moved on. More modern web frameworks have taken a slightly different route and the Angular team have worked hard on giving Angular developers the option to write their apps using this new, modern approach.

So from Angular 15+ the Standalone component was introduced, allowing us as Angular developers to create components like this:

import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';

@Component({
  selector: 'app-home-page',
  standalone: true,
  imports: [RouterLink],
  templateUrl: './home-page.component.html',
  styles: ``,
  template: `<h1 class="text-3xl font-bold underline">Hello world!</h1>
    <button
      [routerLink]="['/contact']"
      routerLinkActive="router-link-active"
      class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
    >
      Add User
    </button>`,
})
export class HomePageComponent {}

In this example, we have everything in the single file. The TypeScript code, though not much of it here, the HTML template and a place for the styles. Also any imports are clearly listed in the imports array, everything is just there. Easy to see and read what is happening in this component.

Comparing with Vue

Not only have I worked on Angular projects, I’ve also spent sometime working with VueJS which is a fantastic framework, with a lot of great features and support.

One thing I did like about Vue was it’s approach to single file components, which at the time were not part of Angular. This is how a Vue component looks:

<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}
</style>

Again everything is in the single file and clear to see. I like how in the Vue version the parts of the component are separated into <script>, <template> and <style> sections, making it easier to see the different parts of the component (this is great if your component has a lot of HTML or TypeScript code).

After working with Vue for a bit and enjoying the single file component structure, when I came back to working on an Angular project I missed the simplicity of the SFC (single file component) that Vue uses. But now with SFC components part of the new Angular I think we will start to see more and more Angular projects take advantage of the SFC architecture.

What are the advantages of the SFC approach

As I see it there are a few advantages to the SFC approach that as Angular developers we can now take advantage of, they include:

  • Easier to read code – now with everything in one file it’s easier to get a complete picture of what the component does and how it works. Ideal for when you are taking over an existing project.
  • Easier to maintain – the code for the component is there in one file, changes are easier to keep track of and refactor when in one file rather than jumping between multiple files
  • It’s easier to explain the code base to another developer – going through the code component by component makes it easier to explain how an application works, rather than going through multiple files trying to explain how the app works.
  • It is easier to test – with modules not being such a core part of Angular now, testing and the mocking for tests are more straight forward to write. Removing a lot of the negative reasons why tests are not written. With less to mock it’s easier to write tests and so there is no reason not to write them.

SFC allow cross framework understanding

One of the main advantages I see to SFC’s is it allows developers from other frameworks to pick up Angular easier – before SFC if you showed a React developer or a Vue developer the codebase of an Angular application it can be overwhelming with the amount of files and listing that this TypeScript file belongs with that HTML file. Now a developer with experience of either React or Vue can understand and relate to this new approach in an Angular project. Also the opposite applies, as an Angular developer who has worked with this SFC architecture when I see a Vue or React code base I find it far easier to relate back to what I already know when looking at the code. I think this will mean that as web developers we can work on multiple projects no matter what the framework used, with SFC the architecture is similar in all cases and we all know HTML, CSS and JavaScript which are the building blocks for all web frameworks.

Thinking of converting your Angular app to use SFC

If you, or your company needs help converting your Angular project to using the new SFC architecture feel free to contact me I can help upgrade your Angular apps to use this new architecture.

Update your package.json file for better tests

By default Angular gives you a couple of commands to run:

npm run start
npm run build
npm run watch
npm run test

These commands get you up and running, you can run the app in the browser, build the final version and run tests in run once.

I like to add a few more commands to my package.json file, these extra ones are:

npm run test:watch
npm run test:coverage
npm run test:ci
npm run lint

These commands give me more options for running my tests, in watch mode, with code coverage and in both watch mode with code coverage. There is also a linting check, which is always helpful for code quality checks.

The full commands in package.json look like this:

"test:watch": "ng test --watch",
"test:coverage": "ng test --code-coverage",
"lint": "ng lint",
"test:ci": "ng test --watch=true --browsers=ChromeHeadless --code-coverage"

Out of all four new commands the most essential one is the test:ci one, which runs my tests in headless mode (which is great as I don’t want to have the Karma runner opening the browser all the time) gives me an overview of all the code covered by tests.

While something like NX will give you more options and use Jest, being able to run these commands in a Angular CLI based project does make running tests easier leaving no reason not to write tests.

Top 10 tips for contractors

Here are my top 10 tips for contractors. I’ve been lucky enough to be contracting now for over 10 years, working with a number of great clients. Over that time I have learnt that there are a couple of tips that I feel contractors should know. They are:

1. Have good interpersonal skills – no matter what tech stack you work with or the type of companies you work with. One thing that you will always work with is other people. You may think that you can just sit at your computer and write the best code ever without being disturbed, but that won’t happen. You need to work with others, discuss ideas with others, listen and maybe advise on how to solve problems at work, maybe help developers who are just starting in their career. You will need to be able to speak to stakeholders and project managers, explaining what it is you are doing, and the most important reason you need to have good interpersonal skills is you need to come across well in the interview. Usually the interview stage can be a one step process so you have that one chance to convince the client that not only can you help them but you will fit within their team.

2. Be good at communicating – this is related to the first tip, showing how important I feel it is, but being good at communicating is essential. You need to be able to speak to all the members of the team you’ve joined, explaining how you are going to solve their problems. You need to show that you are engaged and enthusiastic about the project and the work and this is done through how you communicate with the team. Engaging in meetings, being happy to talk to non-technical team members all help show that you are a real part of the team, even though this maybe be for a short while. I’ve found that contractors who are good at communicating usually get their contracts renewed and other members of the team enjoy working with.

3. Always be learning and willing to learn – while soft skills are extremely important the technical skills you have are as important. If you can’t do the job you’ll soon be found out and the contract will end. A big part of contracting is keeping your skills up to speed, meaning you know about the latest techniques, you have the skills you say you have (there is nothing worse than a contractor who has lied on a CV and can clearly not do what they said). You also need to be willing to learn from others while working on a contract, don’t expect to expect your ‘way’ of doing things (how you build an Angular app for example) be the only way things should be done, yes you have been brought in to help the client but this may be on an existing project and you need to learn and adapt to how things are done. You can’t rewrite everything just because it’s done differently.

4. Be flexible in your approach to work – this, again, is related to the previous point. As a contractor you are basically brought into a project to provide skills that a team currently doesn’t have or augment a team working on a project. If you are there to provide skills that a team doesn’t have chances are you will be working on the part of the tech stack no one else is working on. So you can then approach the work the best way as you see it, that’s why you are there. If you join a team to augment it then you need to be flexible in your approach to work to fit with the team as they are now.

5. Treat contracting as a business – while contracting can lead to working with a client for months at a time, you aren’t a full-time member of staff and you need to treat your contracting as a business. That means you need to keep on top of invoices, submit timesheets on time, email recruitment agencies, keep your accounts up to date, and pay your taxes on time. You also need to work on promoting your business, making sure that your staff (which is you) is paid on time. There is a lot more to contracting than just the coding so see it as a business that you are the owner, the CEO and a member of the staff.

6. Work with agencies, but don’t be completely reliant on them – working with recruitment agencies is a big part of contracting. It will be, at the start, the only way you get work. There are a lot of negative things said about recruiters, but as long as you realise that they are trying to make money for themselves as part of their business and that it is just a business then you shouldn’t have any problems with them. All they want is to see if you have the skills and experience to fit the job spec they have, if you don’t or the client thinks you don’t then they will move onto the next application. Communication is usually one way, you send your CV and wait. If you hear nothing, don’t wait before moving on to the next application. Unfortunately applying for contracts is a numbers game you need to keep applying and if you do fit a role the recruiter will work with you. This doesn’t mean that recruiters are the only way to find work, staying in contact with old clients helps (again these communication and interpersonal skills come in handy) being part of freelancing and the wider tech community can lead to work. Also open source development can lead to work, but this is a long process. So while at first recruiters are the main way of getting work, as a business owner you need to work on the longer game and how you can get work via other methods.

7. Use downtime to learn and develop your skills and business – there will be time when you finish one contract and there isn’t a new one ready to go. This happens, but this time can be used productively. Obviously you will be looking for the next role, but you can also start learning something new, something you’ve seen that you’d like to know more about, something that may eventually lead to a new tech stack to contract in. Or spend the time writing blog posts or eBooks if that’s something you’ve ever wanted to do. Take the time to get organised ready for the next contract, get all your paperwork in order, emails sent, things you planned to do around the house or conference talks you always planned to watch. Anything that helps grow your skills and your business so you are ready to go when the next contract comes around.

8. Help other contractors, they may help you – as you go through your contracting career you will work with other contractors, and it’s always important to stay in contact with them (LinkedIn is ideal for this). If you are contacted about a role that you might not be suitable for but you know someone else who might be. Then put them in contact with the recruiter, it may work out or not, but helping others means that if they see a role you are suitable for they will think of you. This can lead to another way of getting contracts. While contractors are independent doesn’t mean we can’t work together and help one another.

9. Get an accountant – seriously, get an accountant. You might be the best developer or project manager in the land, but when it comes to the finances of your business you need an accountant to guide you through the complex landscape of tax. It’s too much to know all about the things you do, stay on top of the business side of things and be able to do the work an accountant can do for you so you need one. If however you feel the accountant isn’t providing the advice you need, especially at the start of your contracting career, make sure you have one that does even if this means changing accountant. Remember they work for you, you are paying them, so they need to help you, answer your questions, explain things to you to keep everything on track financially as you will have to pay taxes.

10. Eventually focus on one area to specialise in – as time goes by in your contracting career you will need to think about specialising in a certain area. For example, I work with Angular and other developers work with React or Vue. You need to have a skillset that you are known for, so when someone is looking for a contractor to fill a need they have then your name is top of the list. This specialism also means that you can focus on that, learn more about that than other technologies, you can be an expert in everything. Specialising allows you to market yourself around it, for example you can say ‘I am a Go developer’ or a ‘AWS developer’ this can then lead to specialising further to ‘I am an AWS developer working in the communication sector’ or ‘I am a Go developer specialising in API development for large enterprises companies’ or ‘I am an Angular developer who help companies upgrade their projects and architecture allowing new features to be easily developed ‘. Specialising isn’t something you can start with if you are new in your career as a developer, but if you have been a developer for a while and have experience in the area you are going to specialise in, if you start contracting then you can set yourself up as a specialist from the start. This can lead to people being able to find you, know what you offer and know that you are right for their project.

So this is a top 10 list of things I think you need as a contractor. There probably are more I could come up with and more I could go into depth on these, but if you are thinking about contracting then these are somethings I think you should consider.

  1. Have good interpersonal skills
  2. Be good at communicating
  3. Always be learning and willing to learn
  4. Be flexible in your approach  to work
  5. Treat contracting as a business
  6. Work with agencies but don’t be completely reliant on them 
  7. Use downtime to learn and develop your skills and business 
  8. Help other contractors, they may help you
  9. Get an accountant
  10. Eventually focus on one area to specialise in