Skip to main content

Npm package version GitHub

Typescript Usage

The DevCycle Nest.js SDK is written in Typescript and includes a full Typescript interface.

It is also possible to enhance the type safety of the SDK by using the Devcycle CLI to generate a type definition based on the complete set of variables defined in your project. Using this method, you can ensure that your code cannot access a variable key that is not defined in DevCycle, or treat a variable as a different type.

For example, if you have a variable with the key my-variable which is a string type, the following code would produce a type error:

const user = { user_id: 'my_user' }

// type error, can't use a boolean default value since we know it's a string
const myVariableValue = this.devcycleService.variableValue('my-variable', false)

...

// type error, can't use the unknown key 'some-key'
const myVariableValue = this.devcycleService.variableValue('some-key', 'default-value')

...

// this works, since we know this key exists and is a string
const myVariableValue = this.devcycleService.variableValue('my-variable', 'default-value')

Usage

To use this enhanced type-safety, you can define a type containing the variable keys and their types

type VariableTypes = {
'my-variable': string
}

You can then use declare module interface merging to augment the types the SDK uses:

declare module '@devcycle/types' {
interface CustomVariableDefinitions extends VariableTypes {}
}

The keys of VariableTypes must match the keys of the variables defined in DevCycle, and the values must match the expected type of the variable.

You can write this definition manually, but it's recommended to generate it automatically as part of your build process by using the CLI.

CLI

To generate the type definitions with the CLI, you can use the generate types command like so:

dvc generate types

See the documentation for this command

Ensure that the CLI is properly setup and authenticated to your project before running this command. See the CLI docs for further instructions on setting up the CLI.

This command will generate a file called dvcVariableTypes.ts in the configured output directory. The generated output will contain the declare module statement to automatically augment the SDK's types.

Consider configuring this command to run as part of your build process to keep your type definitions up to date with the latest configuration from DevCycle.