Typescript is very powerful in terms of type checking, but sometimes it gets tedious when some types are subsets of other types and you need to define type checking for them.
Let's take an example, you have 2 response types:
UserProfileResponse
interface UserProfileResponse {
id: number;
name: string;
email: string;
phone: string;
avatar: string;
}
LoginResponse
interface LoginResponse {
id: number;
name: string;
}
Instead of defining types of same context LoginResponse and UserProfileResponse, we can define type for UserProfileResponse and pick some properties for LoginResponse.
type LoginResponse = Pick<UserProfileResponse, "id" | "name">;
Let's understand some utility functions that can help you to write better code.
Uppercase
Constructs a type with all properties of Type set to uppercase.
type Role = "admin" | "user" | "guest";
// Bad practice 💩
type UppercaseRole = "ADMIN" | "USER" | "GUEST";
// Good practice ✅
type UppercaseRole = Uppercase<Role>; // "ADMIN" | "USER" | "GUEST"
Lowercase
Constructs a type with all properties of Type set to lowercase. Opposite of Uppercase.
type Role = "ADMIN" | "USER" | "GUEST";
// Bad practice 💩
type LowercaseRole = "admin" | "user" | "guest";
// Good practice ✅
type LowercaseRole = Lowercase<Role>; // "admin" | "user" | "guest"
Capitalize
Constructs a type with all properties of Type set to capitalize.
type Role = "admin" | "user" | "guest";
// Bad practice 💩
type CapitalizeRole = "Admin" | "User" | "Guest";
// Good practice ✅
type CapitalizeRole = Capitalize<Role>; // "Admin" | "User" | "Guest"
Uncapitalize
Constructs a type with all properties of Type set to uncapitalize. Opposite of Capitalize.
type Role = "Admin" | "User" | "Guest";
// Bad practice 💩
type UncapitalizeRole = "admin" | "user" | "guest";
// Good practice ✅
type UncapitalizeRole = Uncapitalize<Role>; // "admin" | "user" | "guest"
Partial
Constructs a type with all properties of Type set to optional.
interface User {
name: string;
age: number;
password: string;
}
// Bad practice 💩
interface PartialUser {
name?: string;
age?: number;
password?: string;
}
// Good practice ✅
type PartialUser = Partial<User>;
Required
Constructs a type consisting of all properties of Type set to required. Opposite of Partial.
interface User {
name?: string;
age?: number;
password?: string;
}
// Bad practice 💩
interface RequiredUser {
name: string;
age: number;
password: string;
}
// Good practice ✅
type RequiredUser = Required<User>;
Readonly
Constructs a type consisting of all properties of Type set to readonly.
interface User {
role: string;
}
// Bad practice 💩
const user: User = { role: "ADMIN" };
user.role = "USER";
// Good practice ✅
type ReadonlyUser = Readonly<User>;
const user: ReadonlyUser = { role: "ADMIN" };
user.role = "USER"; // Error: Cannot assign to 'role' because it is a read-only property.
Record
Constructs a type with a set of properties K of type T. Each property K is mapped to the type T.
interface Address {
street: string;
pin: number;
}
interface Addresses {
home: Address;
office: Address;
}
// Alternative ✅
type AddressesRecord = Record<"home" | "office", Address>;
Pick
Pick only the properties of Type whose keys are in the union type keys.
interface User {
name: string;
age: number;
password: string;
}
// Bad practice 💩
interface UserPartial {
name: string;
age: number;
}
// Good practice ✅
type UserPartial = Pick<User, "name" | "age">;
Omit
Omit only the properties of Type whose keys are in the union type keys.
interface User {
name: string;
age: number;
password: string;
}
// Bad practice 💩
interface UserPartial {
name: string;
age: number;
}
// Good practice ✅
type UserPartial = Omit<User, "password">;
Exclude
Constructs a type with all properties of Type except for those whose keys are in the union type Excluded.
type Role = "ADMIN" | "USER" | "GUEST";
// Bad practice 💩
type NonAdminRole = "USER" | "GUEST";
// Good practice ✅
type NonAdmin = Exclude<Role, "ADMIN">; // "USER" | "GUEST"
Extract
Constructs a type with all properties of Type whose keys are in the union type Extract.
type Role = "ADMIN" | "USER" | "GUEST";
// Bad practice 💩
type AdminRole = "ADMIN";
// Good practice ✅
type Admin = Extract<Role, "ADMIN">; // "ADMIN"
NonNullable
Constructs a type with all properties of Type set to non-nullable.
type Role = "ADMIN" | "USER" | null;
// Bad practice 💩
type NonNullableRole = "ADMIN" | "USER";
// Good practice ✅
type NonNullableRole = NonNullable<Role>; // "ADMIN" | "USER"
Must Read If you haven't
React redux best practice to reduce code
Rahul Sharma ・ May 3 '22
How to cancel Javascript API request with AbortController
Rahul Sharma ・ Apr 9 '22
How to solve REST API routing problem with decorators?
Rahul Sharma ・ Mar 23 '22
Catch me on
Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon
Top comments (7)
In my experience, the developers that partially or don't type at all will make a lot of mistakes along the way. Only the top 10% will still get it right... and I'm extremely generous with that percentage...
Correct typings force developers to think about how their data is structured, it helps them understand exactly how to manipulate and use that data correctly.
Correct typings add a lot of readability to your code and makes maintenance a lot easier. Both those things should trump pretty much anything else in priority. You can get away with a lot less elegant solution as long as the code is readable and easy to maintain.
Correct typings mostly eliminate runtime crashes, which I would argue are the absolute worst kind of bugs.
These things:
increase the mental well being of developers, which in the end:
All this translate to less expanses and more sales.
I would never suggest go without typings as a professional.
some of these if you never know about, its better :) but uppercase and lowercase? that's... interesting, I can see a good scenario for their use that involves directly mapping enums from database, though I still vouch for explicitness
@dirkecker
I fully agree with the first part of your reply.
Java and C# developers tend to be especially "bad" at Javascript because they simply replicate their OOP model to a language that isn't OOP at all. This over-complicates a lot of code and bring a lot of frustrations to those that are from a Javascript background.
From your perspective, I can understand why you'd say typings are not needed.
While not very explicit, that's why I used "Correct typings" in my previous reply. A bunch of class with getter/setter is NOT what I was referring to...
The flaw in your argument is you're taking pretty much what NOT to do with typings and use it to discredit the whole idea of typings. You can use pretty much use anything the wrong way and do very bad things with them, doesn't mean these things should not be used the way they were intended...
Correct typings are like condoms. You don't absolutely NEED them, but you'd be pretty stupid not to use them... You can take all the precautions you want, but you can't control what others bring to the table 😅
Thanks for sharing!
I know it's a controversial opinion, but personally I think that if you're very good, you don't actually need typings or tests.
Typings and tests will slow you down on delivering your code. There's nothing to argue here:
But you're not doing these for you, or at least not for the
current
you.Typings and tests will make
future
you much faster to put yourself back in context and pickup where you left up. Both are an incredible time saver forfuture
you.And as soon as you add another developer or a team to the mix, typings and tests will make things much smoother for everyone.
Tests are the 1st par of the equation. They will show the intended use of the code.
Typings are the 2nd part of the equation. They will provide intellisense in your code editor and provide a safety net before wasting 20 minutes while your tests run.
Typings absolutely brings a lot to the table. They're not a replacement for tests either, both are needed to really give your team a boost.
You don't have to create over-complicated typings, you just need to describe the
inputs
andoutputs
of your function so that others can see at a glance how to use your function.In any case, if this doesn't convince you, well I simply hope you will keep this in mind. Sometimes, it takes time for it to just "click" in place.
Have a good day!
Nice tips. Thanks for sharing.
Well this is Not accurate. I think this just your opinion. I am comming from python and i love typescript. Without typing you can be more productive, yes, at least at the beginning. If a Projects grows, have fun maintaining it. If an api Changes, have fun Finding the bug in pure javascript. At last If you want top know best practices, look at big companies like microsoft, Google and why they use or do not use typescript