Type Script

How to set up TypeScript for Prysm

TypeScript is a widely-used tool for type-checking, auto-completion and code validation. It is especially useful for Prysm because it allows you to set up your development environment to be specifically tailored to the Cohtml library, thus helping ease learning the various supported, unsupported, or extra features it provides compared to a typical web browser.

Installation

You can install typescript via

npm i -g typescript

Using TypeScript definitions

You can find all files listed below inside the Samples\uiresources\library\ folder of your Prysm package. The contents of the folder are as follows:

  • DOM TypeScript definitions (cohtml.lib.dom.d.ts) - these definitions contain the DOM properties implemented in Prysm
  • Cohtml.js typescript definitions (cohtml.d.ts) - this file contains extra definitions, used by the Cohtml library for features such as databinding
  • The cohtml.js file itself - the exact version of this file used to generate the definitions

You need to add your own tsconfig.json file to this folder as well, in which you need to specify the index.js file used in your game. In this case, we assume that index.js is some “main” file in your game UI.

tsconfig.json

{
    "files": [
        "src/index.js"
    ],
    "compilerOptions": {
        "outDir": "dist",
        "lib": [
            "ES5",
            "ES2015.Iterable",
            "ES2015.Promise",
            "ES2015.Core"
        ],
        "allowJs": true,
        "checkJs": true,
        "noEmit": true,
        "module": "ES2015",
        "target": "es2015",
        "allowSyntheticDefaultImports": true,
    },
    "include": [
        "lib/**/*.d.ts"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

The lib option allows you to specify which of the default library definitions we want to use. We don’t need the DOM definitions that TypeScript comes with because we’ll use the ones for Prysm.

The file structure should look similar to this:

|-tsconfig.json
|
+---lib
|   |   cohtml.lib.dom.d.ts
|   |   cohtml.d.ts
|
\---src
    |    index.html
    |    index.js
    |    cohtml.js

You can now directly import the cohtml.js inside index.js.

import './cohtml.js';

If you receive the following error inside cohtml.js - Cannot find name 'global' then you need to run the npm install @types/node --save-dev command in your root folder.

That’s it. You should be good to go. You can now use tsc to run a type check. If your IDE supports IntelliSense you’ll see the errors even before compilation.

ESLint with TypeScript and React

When you are using TypeScript with React project and you have configured ESLint make sure to disable the no-undef rule. If this rule is not disabled then the linter may show an error that 'engine' is not defined.

.eslintrc.json

    {
        ...
        "rules": {
            ...
            "no-undef": "off",
            ...
        }
    }