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)

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:

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 at runtime when assignments occur

  • 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

Was this helpful?