Using TypeScript
While CAP itself is written in JavaScript, it's possible to use TypeScript within your project as outlined here.
Enable TypeScript Support
Follow these steps to add TypeScript support:
Install typescript packages globally:
shnpm i -g typescript ts-node tsxAdd a basic tsconfig.json file to your project:
shcds add typescriptYou can modify this configuration file to match your project setup. See the official TypeScript documentation for more details. Note that adding the
typescriptfacet,cds-typeris also automatically added to your project.
Writing TypeScript Files
Once you have setup everything correctly, you can start using TypeScript files instead of JavaScript files. This setup applies for service handlers, and to a custom server.ts file, or database init.ts seeding files as well.
Samples
For a full TypeScript application, check out the SFlight application. It features both CAP service handlers and client-side code for SAP Fiori Elements written in TypeScript.
Developing TypeScript Projects
Using cds watch Since @sap/cds-dk 8.6.0
Preferably use cds watch in a TypeScript project as if it was a JavaScript project. It detects TypeScript mode based on a tsconfig.json and run cds-tsx under the hood.
cap/sflight $ cds watch
Detected tsconfig.json. Running with tsx.
...
[cds] serving TravelService { impl: 'srv/travel-service.ts', path: '/processor' }
...The same applies to cds serve.
Using cds-tsx Since @sap/cds-dk 8.2.0
Alternatively, you can use the cds-tsx CLI command instead of cds for automatic TypeScript transpilation:
cds-tsx watchcds-tsx serveUnder the hood, the tsx engine is used to run the files instead of the default node engine. Install it globally with:
npm i -g tsxNot for production
Use cds-watch and cds-tsx / tsx during development only. For productive usage, always precompile TypeScript code to JavaScript for best performance and use cds-serve as usual.
Using cds-ts
Much like cds-tsx, you can also use the cds-ts CLI command:
cds-ts watchcds-ts serveIt uses the ts-node engine under the hood.
tsx or ts-node?
In general, tsx is the better choice, as tsx is considerably faster than ts-node because it doesn't perform type checks. See a closer comparison between the two of them.
Testing with ts-jest
Run your Jest tests with preset ts-jest without precompiling TypeScript files.
Install
ts-jestlocally:shnpm install -D ts-jestTell Jest to use the preset
ts-jest, for example, in your jest.config.js:jsmodule.exports = { preset: "ts-jest", globalSetup: "./test/setup.ts" };Set
CDS_TYPESCRIPTenvironment variable:This is necessary, because it isn't possible to programmatically detect that the preset
ts-jestis used and we've to know whether we need to look for .ts or .js files.File ./test/setup.ts, content:
jsmodule.exports = async () => { process.env.CDS_TYPESCRIPT = "true"; };Run your tests as usual:
shjest
Building TypeScript Projects
A dedicated build task for cds build is provided as part of the cds-typer package.
Learn more about integrating it into your build process.
Running Built Projects Locally
The artifacts deployed to the various cloud platforms are generated in the gen/srv/ folder. So, to test the application as it runs on the cloud start your application from the gen/srv/ folder:
cds build # to create the js files
cd gen/srv && npm startLearn more on running a project from build results.
TypeScript APIs in @sap/cds Since @sap/cds 8.0.0
The package @cap-js/cds-types contains all TypeScript declarations for @sap/cds APIs. These declarations are used automatically when you write TypeScript files, but also enable IntelliSense and type checking for standard JavaScript development in Visual Studio Code. Just add the @cap-js/cds-types package to your project as follows:
npm add @cap-js/cds-typesUse the Typescript declarations like this:
import { Request } from '@sap/cds'
function myHandler(req: Request) { }Types are available even in JavaScript through JSDoc comments:
/**
* @param { import('@sap/cds').Request } req
*/
function myHandler(req) { }Type Imports
Import types through the cds facade class only:
Good:
import { ... } from '@sap/cds'Bad:
Never code against paths inside @sap/cds/apis/:
import { ... } from '@sap/cds/apis/events'Community
Help us improve the types
We invite you to contribute and help us complete the typings as appropriate. Find the sources on GitHub and open a pull request or an issue.
Still, as @sap/cds is a JavaScript library, typings aren't always up to date. You should expect a delay for typings related to the latest release, even gaps, and errors.
Generating Model Types Automatically
The cds-typer package offers a way to derive TypeScript definitions from a CDS model to give you enhanced code completion and a certain degree of type safety when implementing services.
class CatalogService extends cds.ApplicationService { init() {
const { Book } = require('#cds-models/sap/capire/bookshop')
this.before('CREATE', Book, req => {
req.data.… // known to be a Book. Code completion suggests:
// ID (number)
// title (string)
// author (Author)
// createdAt (Date)
// …
})
}}You can find extensive documentation in a dedicated chapter, together with a quickstart guide to get everything up and running.