What is the benefit of using abstract types in TypeScript with Hygraph?
Using abstract types in TypeScript with Hygraph helps maintain a consistent data structure across your application. By importing types from a central file, developers avoid rewriting code, making the codebase more maintainable and readable. This approach ensures that objects like Movie retain their proper shape across different components. Learn more.
How can I abstract types and interfaces in TypeScript when building with Hygraph?
You can abstract types and interfaces in TypeScript by storing all definitions in a single types.ts file and importing them wherever needed. This method reduces redundancy and keeps your codebase organized. For example, in the Hygraphlix demo, all types are stored in types.ts and imported into relevant components. See the abstract-types branch.
Where can I learn more about abstract typing in TypeScript with Hygraph?
You can learn more about abstract typing in TypeScript on the Hygraph blog: Abstract Types in TypeScript. The blog provides examples, best practices, and code samples for organizing types and interfaces in your projects.
What TypeScript types are defined in the Astro project with Hygraph?
The Astro project with Hygraph defines TypeScript types for product and list of products. This helps ensure type safety and consistency when working with product data. Learn more.
How does Hygraph improve code readability in TypeScript projects?
Hygraph improves code readability in TypeScript projects by allowing developers to import types from a central types.ts file. This eliminates the need to redefine types in every file, ensuring that objects like Movie maintain their proper shape across different components. This approach makes the codebase cleaner and easier to maintain. Read more.
Where can I find the abstract-types branch of the Hygraph repo?
The abstract-types branch of the Hygraph repo is available on GitHub. You can view it here for a practical example of abstracting types in a real project.
Features & Capabilities
What features does Hygraph offer for developers?
Hygraph offers a GraphQL-native architecture, content federation, scalability, and a wide range of integrations including Netlify, Vercel, Shopify, AWS S3, Cloudinary, and more. It provides a powerful GraphQL API for efficient content management and delivery. See all features.
Does Hygraph provide an API for content management?
Yes, Hygraph provides a powerful GraphQL API that allows you to fetch and manage content efficiently. You can learn more about it at the Hygraph API Reference.
What integrations are available with Hygraph?
Hygraph offers integrations with hosting and deployment platforms (Netlify, Vercel), eCommerce solutions (Shopify, BigCommerce, commercetools), localization tools (Lokalise, Crowdin, EasyTranslate, Smartling), digital asset management (AWS S3, Cloudinary, Bynder, Aprimo, Mux, Scaleflex Filerobot), personalization and AB testing (Ninetailed), artificial intelligence (AltText.ai), and more. See all integrations.
Security & Compliance
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant, ISO 27001 certified, and GDPR compliant. These certifications ensure enterprise-grade security and data protection for all users. Learn more about security features.
How does Hygraph protect sensitive data?
Hygraph protects sensitive data with features such as SSO integrations, audit logs, encryption at rest and in transit, and sandbox environments. These measures help meet regulatory standards and safeguard user information. See details.
Pricing & Plans
What is Hygraph's pricing model?
Hygraph offers a free forever Hobby plan, a Growth plan starting at $199/month, and custom Enterprise plans. For more details, visit the pricing page.
Use Cases & Customer Success
Who can benefit from using Hygraph?
Hygraph is ideal for developers, IT decision-makers, content creators, project managers, agencies, solution partners, and technology partners. Companies that benefit most include modern software companies, enterprises looking to modernize their tech stack, and brands aiming to scale across geographies or improve development velocity. See case studies.
Can you share specific case studies or success stories of customers using Hygraph?
Yes, Hygraph has several success stories. For example, Komax achieved a 3X faster time to market, Autoweb saw a 20% increase in website monetization, and Samsung improved customer engagement with a scalable platform. Dr. Oetker enhanced their digital experience using MACH architecture. Explore more success stories.
What industries are represented in Hygraph's case studies?
Hygraph's case studies cover industries such as food and beverage, consumer electronics, automotive, healthcare, travel and hospitality, media and publishing, eCommerce, SaaS, marketplace, education technology, and wellness and fitness. See all case studies.
Who are some of Hygraph's customers?
Hygraph's customers include Sennheiser, HolidayCheck, Ancestry, Samsung, Dr. Oetker, Epic Games, Bandai Namco, Gamescom, Leo Vegas, and Clayton Homes. See more customers.
Pain Points & Solutions
What problems does Hygraph solve?
Hygraph solves problems such as reducing reliance on developers for content updates, modernizing legacy tech stacks, addressing conflicting needs of global teams, and improving user experience for content creation. Financially, it lowers operational costs, speeds up time-to-market, and supports scalability. Technically, it simplifies development workflows, streamlines query management, and resolves cache and integration challenges. Learn more.
How does Hygraph address pain points for different personas?
Hygraph tailors solutions for different personas: Developers benefit from reduced boilerplate code and streamlined queries; Content creators and project managers gain independence from developers and a user-friendly interface; Business stakeholders see lower operational costs, easier scalability, and faster speed to market. See details.
What KPIs and metrics are associated with the pain points Hygraph solves?
KPIs include time saved on content updates, number of updates without developer intervention, system uptime, speed of deployment, consistency across regions, user satisfaction scores, reduction in operational costs, ROI, time to market, maintenance costs, scalability metrics, and performance during peak usage. Read more about CMS KPIs.
Support & Implementation
How easy is it to get started with Hygraph?
Hygraph is designed for easy onboarding, even for non-technical users. You can sign up for a free account and access resources like documentation, video tutorials, and onboarding guides. For example, Top Villas launched a new project in just 2 months. Get started here.
What support and training does Hygraph offer?
Hygraph provides 24/7 support via chat, email, and phone. Enterprise customers receive dedicated onboarding and expert guidance. All users have access to documentation, video tutorials, webinars, and a community Slack channel. Contact support.
Where can I find Hygraph's technical documentation?
Comprehensive technical documentation is available at Hygraph Documentation, covering everything you need to know about building and deploying projects with Hygraph.
Blog & Community
Where can I find the Hygraph blog?
You can visit the Hygraph Blog for news, developer tutorials, and essential guides to content modeling and TypeScript best practices.
Who authored the blog 'WordPress Alternatives'?
The blog 'WordPress Alternatives' was authored by Jing Li, Content Marketing Manager at Hygraph. Read the blog.
How can I join the Hygraph community?
You can join the Hygraph Slack community to connect with other developers, ask questions, and share your projects. Join the Slack community.
Everything in its right place: How to abstract types in TypeScript
TypeScript (Ts) is a strongly typed programming language that compiles to JavaScript, so it can used anywhere JavaScript (Js) is used, such as a browser. Learn when and how to abstract your types and interfaces when using Typescript.
Written by Lo
on Feb 12, 2024
TypeScript (Ts) is a strongly typed programming language that compiles to JavaScript, so it can be used anywhere JavaScript (Js) is used, such as a browser. These qualities and the ability to work at any scale of application or tooling make it ideal for integrating a front-end with a CMS. You might be thinking, if it runs like Javascript and converts to it in the end, why not use JavaScript? The magic of TypeScript is that it adds strictly defined syntax called a type system that creates a tighter connection with your CMS and helps you catch errors faster and earlier.
When using TypeScript, you can organize your interfaces and types in various ways.
You can store interfaces on the main file that uses them directly.
You can explicitly export and import types from .ts files like any other class, function, or object. These files may be TypeScript files that only contain types. You can keep these files in the root folder or locally in the specific directory.
When you’re new to Typescript, keeping your types close at hand can give you a sense of security. It also keeps you from over-optimizing too early. When you have your first set of types, you can write them in place, and when you need to use them again, abstract them into a new file. When you’ve architected a few projects like this, you may already know when you’ll want to do this and abstract things from the beginning.
When you’re new to Typescript, keeping your types close at hand can give you a sense of security. It also keeps you from over-optimizing too early. When you have your first set of types, you can write them in place, and when you need to use them again, abstract them into a new file. When you’ve architected a few projects like this, you may already know when you’ll want to do this and abstract things from the beginning.
Looking at a TypeScript example: Hygraphlix
In the first iteration of Hygraphlix, a movie streaming platform demo built with Hygraph and NextJS 14, I placed my types and interfaces in the main file where they were used. I am still somewhat new to TypeScript, and having my types in the same place as the rest of my code helped me understand their connection to the Hygraph CMS and my NextJS code.
The code below creates the Hygraphlix Homepage that features the Top 8 movies on the platform by querying the first eight movies from Hygraph.
//Homepage with movies: app/page.js
import{Link}from"@nextui-org/link";
import{Snippet}from"@nextui-org/snippet";
import{Code}from"@nextui-org/code";
import{ button as buttonStyles }from"@nextui-org/theme";
// Declare movie interface and map over movies list to render in movie cards
(movie:{
id: string;
federateMovie:{
data:{
Title: string;
Poster: string;
alt: string;
Genre: string;
Director: string;
};
};
slug: string;
moviePoster:{
height: number;
width: number;
url: string;
};
})=>(
<MovieCard
key={movie.id}
Title={movie.federateMovie.data.Title}
Poster={movie.federateMovie.data.Poster}
moviePoster={movie.moviePoster}
alt={movie.federateMovie.data.Title}
Genre={movie.federateMovie.data.Genre}
Director={movie.federateMovie.data.Director}
slug={movie.slug}
/>
)
)}
</div>
</section>
</div>
</>
);
}
The async Home function retrieves all the featured movie data and maps them to a MovieCard component. The TypeScript Movie interface definition is located inside of the movies map function.
Zooming in on our Movie interface definition
// Movie TypeScript interface definition
interfaceMovie{
id: string;
federateMovie:{
data:{
Title: string;
Poster: string;
alt: string;
Genre: string;
Director: string;
};
};
slug: string;
moviePoster:{
height: number;
width: number;
url: string;
};
}
In the Movie Interface definition, we are defining the Movie object and properties like id, federateMovie, slug, and moviePoster. The federateMovie object is a remote source coming into Hygraph from OMDB, and open-source movie database that contains a data object with properties like Title, Poster, alt, Genre, and Director The moviePoster property is also an object that contains height, width, and url.
#Abstracting your types and interfaces into the same file
You can get started quickly with abstracting by declaring your types in the file where they will be used, but not directly in your function. Looking at the Homepage code again, you could declare the Movie interface above the async function Home() , like so:
// Map over movie object list to render in movie cards
<MovieCard
key={movie.id}
Title={movie.federateMovie.data.Title}
Poster={movie.federateMovie.data.Poster}
moviePoster={movie.moviePoster}
alt={movie.federateMovie.data.Title}
Genre={movie.federateMovie.data.Genre}
Director={movie.federateMovie.data.Director}
slug={movie.slug}
/>
)
)}
</div>
</section>
</div>
</>
);
}
In this location and in line with the function, it is easier to understand how the Movie interface helps ensure that components receive the correct props and that objects have the correct structure as it strictly defines the shape of our query result or data object and the props that will be used in our Next app. This can help catch errors at compile time rather than runtime, making the code more robust and easier to debug.
While putting your types and interfaces directly into the file where they are used is okay, what happens when you want to use the Movie object again? You would have to define it in every new file that uses it. This can get complicated and messy very quickly when you have a large application. Another way to organize your types and interfaces when using TypeScript is to have a file that contains all of our definitions and import it into the files that require it. So, let’s do that!
#Abstracting your types and interfaces into a single file
To put all the types used in the Hygraphlix Next app together, go to the folder called types in the root of the project and rename the index.ts file to types.ts and copy and paste the types from the app routes and component directories. When complete, the file should match the below code:
// Map over movie object list to render in movie cards
<MovieCard
key={movie.id}
Title={movie.federateMovie.data.Title}
Poster={movie.federateMovie.data.Poster}
moviePoster={movie.moviePoster}
alt={movie.federateMovie.data.Title}
Genre={movie.federateMovie.data.Genre}
Director={movie.federateMovie.data.Director}
slug={movie.slug}
/>
)
)}
</div>
</section>
</div>
</>
);
}
In the above code, we are now importing the Movie type from the types.ts file. Our Home function awaits the result of the getFeaturedMovies function and assigns it to the movies variable that contains the Movie object that we defined in our type definitions. We map over the movies array and pass the necessary props from our Movie object to render the list of movies. Not only is our homepage code a bit cleaner, but we have also removed the redundancy of having to define our types every time they are used in a new file. Let’s say, for example, we want to create a ‘related movie’ area on each individual movie page; by importing the types, we get the proper shape of Movie object without having to rewrite all the code.
There are many approaches and opinions about where you should put your types when using Typescript. Some developers even autogenerate their types, while some prefer placing their types in the route folder where they will be used rather than one file at the root level. Ultimately, what matters is your own comfort level with your code and making sure your code is readable to the developer who comes along after you have moved on to another project. Clone the Hygraphlix project and frontend code and practice separating the types. To view Hygraphlix with all types stored in types.ts, go to the abstract-types branch of the repo. If you have any questions or feedback, find me in the community!
Join the community
Need help? Want to show off? Join the Slack community and meet other developers building with Hygraph
Lo is Hygraph's Senior Developer Relations Specialist. They focus on developer education around Headless CMS, JS-based frontends, and API technologies as well as the dynamic cross-functional relationship between developers and content professionals.
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.