For the complete documentation index, see llms.txt. This page is also available as Markdown.

Typed Variables

OSL allows you to declare variables with specific types, providing type safety and better code clarity. This feature enables you to enforce that a variable or object property can only hold values of a specified type.

Syntax

For variables:

type variableName = value

For object properties:

type objectName.propertyName = value

Supported Types

OSL supports the following type annotations for variables:

  • string - Text values

  • number - Numeric values (integers and decimals)

  • boolean - Logical values (true/false)

  • array - JSON arrays

  • object - JSON objects

  • function - Function objects

  • any - Any type (default if no type is specified)

  • auto - Infer the variable type from the initial value

You can also suffix any type with ? to allow it to be null or that type

Examples

Basic Type Declarations

Typing Object Properties

You can also type specific properties of objects:

Type Enforcement

Once a variable or property is typed, OSL enforces that type for all future assignments:

Working with Functions

Typed variables work well with functions that expect specific types:

Type Conversion

If you need to change a value's type, you can use conversion methods:

Optional Types

If you add a ? to the end of a type it makes it optional and allows the variable to be set to null or to that type.

This is super useful for when you want to initialise a typed variable early and set its value later.

Benefits of Typed Variables

  1. Error Prevention - Catch type-related errors early

  2. Code Clarity - Make your intentions clear about what type a variable should hold

  3. Better Tooling Support - Enable better code completion and hints

  4. Self-Documenting Code - Types serve as documentation for your variables

  5. Improved Maintainability - Makes code easier to understand and modify

Notes

  • Type annotations are optional - you can mix typed and untyped variables

  • Type checking happens during compilation where the type is known, and the generated program enforces typed storage

  • Once a variable is typed, that type is enforced for the lifetime of the variable

  • Type annotations do not affect the variable's value, only what values it can accept

  • Using typed variables can help catch bugs early and make your code more robust

Last updated