Studio Developer Manual / Version 2210
Table Of Contents
Having a Config type allows to specify typed Config objects in TypeScript by using a
type assertion (we use the <...>
syntax here rather than the
as
keyword 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 still be added without a type error:
import Config from "@jangaroo/runtime/Config"; import MyClass from "./MyClass"; ... const myClassConfig = <Config<MyClass>>{ // inherited from Config<Component>: id: "4711", // MyClass Config property: configOption1: "bar", // an undeclared property does *not* lead to a type error: untyped: new Date(), // type error: '"42" is not assignable to type number[]': configOption2: "42", }; ...
Example 5.11. 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"; ... // first 'Config' is the utility type, second the utility function: const myClassConfig: Config<MyClass> = Config<MyClass>({ // inherited from Config<Component>: id: "4711", // MyClass Config property: configOption1: "bar", // an undeclared property now *does* lead to a type error: untyped: new Date(), // type error: '"42" is not assignable to type number[]': configOption2: "42", }); ...
Example 5.12. Preventing use of untyped properties
We just added a type annotation to myClassConfig
for clarity. You can omit it and 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 exactly that Config object.
Since TypeScript is more strict when checking the type of function arguments 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.