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:
For object properties:
Supported Types
OSL supports the following type annotations for variables:
string
- Text valuesnumber
- Numeric values (integers and decimals)boolean
- Logical values (true/false)array
- JSON arraysobject
- JSON objectsfunction
- Function objectsany
- 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
Error Prevention - Catch type-related errors early
Code Clarity - Make your intentions clear about what type a variable should hold
Better Tooling Support - Enable better code completion and hints
Self-Documenting Code - Types serve as documentation for your variables
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?