Typed Variables
Last updated
// Typed variable declarations
string name = "Alice"
number age = 30
boolean isActive = true
array items = [1, 2, 3]
object settings = { theme: "dark" }
// Attempting to assign the wrong type will cause an error
name = 42
// Error: Cannot assign number to string variable// Create an object
user = {
name: "Bob",
age: 25,
active: true
}
// Type a property
string user.name = "Charlie"
// Works fine
number user.age = 30
// Works fine
// This would cause an error
number user.name = 50 // Error: Cannot assign number to string property// Initial declaration with type
number score = 100
// Valid reassignments
score = 200
// Works fine
score = score + 50
// Works fine
// Invalid reassignments
score = "High"
// Error: Cannot assign string to number variable
score = true
// Error: Cannot assign boolean to number variable// Function that expects a number
def double(number val) (
return val * 2
)
// Using typed variables with functions
number value = 5
result = double(value)
// Works fine
string text = "10"
result = double(text)
// Error: Function expected number but got stringstring textValue = "42"
number numValue = textValue.toNum() // Convert string to number
number price = 19.99
string priceTag = price.toStr() // Convert number to stringstring myString = null
// will error
string? myString = null
// will succeed