Typescript Tips and Tricks

By achimoraites Jan 28, 2020

Typescript Tips and Tricks

Here are two Typescript tricks to make your life as a software developer easier.

Create Flexible interfaces

Ever wondering if you can find a middle ground between the any type and of a specific type/interface ?

The answer is yes! You can make an interface that contains any number of attributes of a specific type while having the ability to have any attribute name:

interface Person {
  name: string;
  age: number;
}

interface FlexInterface {
  [index: string]: Person;
}

// now you can use it like
const Group: FlexInterface = {
  alice: {
    name: 'Alice Byers',
    age: 24
  },
  brian: {
    name: 'Brian Sanders',
    age: 16
  }
};

// still this will fail!

const Group2: FlexInterface = {
  alice: {
    name: 'Alice Byers',
    age: 24
  },
  brian: {
    name: 'Brian Sanders',
    age: 16
  },
 // Type 'string' is not assignable to type 'Person'
  matt: 'Mathew'
};

Taking advantage of this technique you can create flexible types without using type any !

Create a type that has a partial match of another type

This effectively means that we can match any number of properties of a given type:


interface Person {
  name: string;
  age: number;
}

type PartialPerson = Partial<Person>;

function updatePerson(personToUpdate: Person, attributes: PartialPerson) {
  return { ... personToUpdate, ...attributes };
}

let person: Person = {
  name: 'John Doe',
  age: 8
};


// this works as expected
const attrs1: PartialPerson = {
  age: 38
};

// this will fail
const attrs2: PartialPerson = {
  hobbies: ['chess', 'swimming', 'coding']
};

person = updatePerson(person, attrs1);

Happy coding 😄

Credits

Photo by Yogendra Singh from Pexels


Related Articles