DEV Community

Cover image for TypeScript Best Practices — Part 1
Stephen Gbolagade
Stephen Gbolagade

Posted on

TypeScript Best Practices — Part 1

Having a source of truth for your Typescript file will not only make your code cleaner, but it will also help you fix any Type conflict that may arise as a result of duplicate types.

Do you know you can do this in TypeScript to make your code cleaner?

interface Author {
 id: string
 name: string
 posts: {
  title: string
  slug: string
}[]
}
Enter fullscreen mode Exit fullscreen mode

Then:

type AuthorPosts = Author["posts"]
Enter fullscreen mode Exit fullscreen mode

OR

type AuthorPosts = Pick<Author, "posts">
Enter fullscreen mode Exit fullscreen mode

instead of doing this repetition again:

interface AuthorPost {
 posts: {
  slug: string
  title: string
}[]
}
Enter fullscreen mode Exit fullscreen mode

Note:

Snippet A and B extract the posts types from Author, the results are similar. One extract the full post type as an object while the other one extract only the child of the type.

Snippets:
Typescriptsample

Try it!

Top comments (0)