peScript in JavaScript client library
We rewrote our JavaScript client library in TypeScript to provide better type safety for users of contentful.js
. Typescript support allows us to keep types constantly up-to-date. The following features are added:
Query type support—Autosuggestions based on your Contentful content model allow you to know exactly which search parameters you can use in your requests.
Chained client modifiers—An option to modify the response shape of your CDA calls, and thus get predictable response type support.
This tutorial walks you through some examples of these features' usage.
Prerequisites
To successfully work with TypeScript in contentful.js
, you must be familiar with the JavaScript client library and have a basic TypeScript project set up in strict mode. To learn about the JavaScript client library, refer to Getting Started with Contentful and JavaScript.NOTE: If you already have a project which is using the previous version of contentful.js
, refer to Migrate from the old to the new version of contentful.js for migration instructions.
Query types
To understand how query type support works, let’s consider the following example:Let’s say you need to query entries of a content type BlogPost
which has several fields of different types. In the previous versions of contentful.js
, when composing the query object to pass to getEntries
, you would have to manually check which fields existed, and look up which operators out of multiple CDA search parameters are allowed for which field type.With TypeScript, autosuggestions are dynamically displayed as you type the names of the fields, so you can select the ones you need from the drop-down.The steps listed below explain how to query entries of our example content type BlogPost
with TypeScript.To query entries of a content type BlogPost
:
Define the shape of this content type as a TypeScript type or interface.
NOTE: We recommend to automate this step instead of doing it manually. To learn how to automatically generate types for your Contentful content models, refer to Generating type definitions for content types.Copytype BlogPostSkeleton = { contentTypeId: "blogPost", fields: { productName: Contentful.EntryFieldTypes.Text, image: Contentful.EntryFieldTypes.Asset, price: Contentful.EntryFieldTypes.Number, categories: Contentful.EntryFieldTypes.Array<Co