DEV Community

Cover image for Typescript Tips and Tricks
Achilles Moraites
Achilles Moraites

Posted on

Typescript Tips and Tricks

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

Make an interface that has any number of attributes of a specific type

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'
};

Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

I you have some tips and tricks of your own feel free to share them in the comments below!

Happy coding :)

Credits

Photo by Yogendra Singh from Pexels

Top comments (1)

Collapse
 
teekay profile image
TK

If I'm not wrong, Partial transforms all the type properties into optional properties. I prefer using the Pick utility. That way, I get the types I need but also keeping all the properties required.