close

Filter

loading table of contents...

CoreMedia Content Cloud v11 Upgrade Guide / Version 2110

Table Of Contents
7.3.1.6.3.2 Specifying Strictly Typed Config Objects in TypeScript

Having a Config type allows to specify typed Config objects in TypeScript by using a type assertion (we use the <...> syntax here to place the type in front), taking advantage of type checks and IDE support. The following example shows that type errors are detected for existing properties, however, arbitrary undeclared properties can be added without a type error:

import Config from "@jangaroo/runtime/Config";
import MyClass from "./MyClass";

...
    const myClassConfig = <Config<MyClass>>{
      id: "4711",  // inherited from Component._
      configOption1: "bar",  // MyClass Config property
      untyped: new Date(),  // an undeclared property does *not* lead to a type error!
      configOption2: "42"  // type error: '"42" is not assignable to type number[]'
    };
... 

Example 7.14.  TypeScript detecting type errors for existing properties


Being able to use undeclared properties without warning is not desirable. Fortunately, in TypeScript, it is possible to specify the signature of a generic Config type-check function to prevent using untyped properties. You get access to this function through the same imported Config identifier (remember, TypeScript allows to declare a value and a type with the same identifier).

import Config from "@jangaroo/runtime/Config";
import MyClass from "./MyClass";

...
    const myClassConfig: Config<MyClass> = Config<MyClass>({ // first 'Config' is the utility type, second a function!
      id: "4711",  // inherited from Component._
      configOption1: "bar",  // MyClass Config property
      untyped: new Date(),  // an undeclared property now *does* lead to a type error!
      configOption2: "42"  // type error: '"42" is not assignable to type number[]'
    });
... 

Example 7.15.  Preventing use of untyped properties


We just added the type of myClassConfig for clarity, you can leave that to TypeScript's type inference.

The first Config (after the colon) is the utility type from above, but the second Config is a call to the generic Config type-check function, which takes as argument a Config object of the corresponding Config type MyClassConfig and returns that Config object complemented by xclass / alias / xtype properties.

Since TypeScript is more strict when checking the type of function argument than when a type assertion is used, this solution prevents accidental access to untyped properties. In the example, the property untyped would now be marked as an error, because it does not exist in the Config type.

Search Results

Table Of Contents
warning

Your Internet Explorer is no longer supported.

Please use Mozilla Firefox, Google Chrome, or Microsoft Edge.