Topaz Data Types

Master Topaz powerful type system. Learn everything about Topaz types from basic primitives to advanced generics, providing both type safety and expressiveness.

Topaz combines a powerful static type system with intelligent type inference to enable safe yet concise code writing. The compiler infers types automatically when you don't specify them, but you can be explicit when needed. 🎯

🔢 Primitive Types

Integers and Floats

// Integer types
let age: int = 25
let bigNumber: bigint = 9999999999999999999

// Float types  
let price: float = 19.99
let preciseNumber: double = 3.141592653589793

// Simple with type inference
let score = 95        // inferred as int
let average = 87.5    // inferred as float

Boolean

let isActive = true
let hasAdminRights = false

// Used in conditionals
if isActive {
    print("Service is active")
}

Characters and Strings

// Character (single)
let grade: char = 'A'
let emoji: char = '🎉'

// String
let name = "John Topaz"
let longSentence = "Welcome to Topaz, the language where code becomes poetry!"

// String interpolation
let greeting = "Hello, {name}! Nice weather today."
print(greeting)  // "Hello, John Topaz! Nice weather today."

📊 Collection Types

Arrays

// Array declaration and initialization
let numbers: [int] = [1, 2, 3, 4, 5]
let names = ["Alice", "Bob", "Charlie"]  // inferred as [string]

// Array manipulation
let first = numbers[0]           // 1
numbers.push(6)                  // [1, 2, 3, 4, 5, 6]
let length = numbers.length()    // 6

// Functional style operations
let squares = numbers.map(x => x * x)
let evens = numbers.filter(x => x % 2 == 0)

Objects

// Object definition
let user = {
    name: "John Topaz",
    age: 28,
    email: "john@example.com",
    isActive: true
}

// Property access
print(user.name)               // "John Topaz"
user.age = 29                  // value change

// Object with methods
let calculator = {
    value: 0,
    add: function(x: int) -> int {
        this.value += x
        return this.value
    },
    multiply: function(x: int) -> int {
        this.value *= x
        return this.value
    }
}

calculator.add(10).multiply(2)      // method chaining

🏗️ Advanced Types

Option Type

// Option type for null safety
let searchResult: Option<string> = None
let username: Option<string> = Some("admin")

// Safe handling with pattern matching
match username {
    case Some(name) => print("Welcome, {name}!")
    case None => print("Login required")
}

// Safe handling with chaining
let length = username?.length ?? 0

Result Type

// Result type for error handling
function readFile(path: string) -> Result<string, Error> {
    if fileExists(path) {
        Ok(readFileContent(path))
    } else {
        Err(Err("File not found"))
    }
}

// Safe error handling
match readFile("data.txt") {
    case Ok(content) => print("File content: {content}")
    case Err(error) => print("Error occurred: {error.message}")
}

Union Types

// Type that can be one of several types
type ID = int | string
type Status = "pending" | "processing" | "completed" | "failed"

let userID: ID = 12345
let taskStatus: Status = "processing"

// Type-specific handling with pattern matching
function displayID(id: ID) -> string {
    match id {
        case int => "Numeric ID: {id}"
        case string => "String ID: {id}"
    }
}

🧬 Generic Types

Generic Functions

// Generic function with type parameters
function createArray<T>(value: T, count: int) -> [T] {
    let result: [T] = []
    for i in 0..count {
        result.push(value)
    }
    return result
}

let numberArray = createArray(42, 5)      // [42, 42, 42, 42, 42]
let stringArray = createArray("hello", 3) // ["hello", "hello", "hello"]

Generic Structs

// Generic struct definition
struct Container<T> {
    value: T,
    
    function setValue(newValue: T) {
        this.value = newValue
    }
    
    function getValue() -> T {
        return this.value
    }
}

let numberContainer = Container { value: 100 }
let stringContainer = Container { value: "Hello" }

🎨 Type Aliases

// Give simple names to complex types
type UserInfo = {
    name: string,
    age: int,
    email: string,
    permissions: [string]
}

type CallbackFunction = function(data: string) -> void
type StateUpdater<T> = function(prevState: T) -> T

// Usage example
let admin: UserInfo = {
    name: "Admin User",
    age: 35,
    email: "admin@topaz.ooo",
    permissions: ["read", "write", "delete"]
}

🔄 Type Conversion

// Explicit type conversion
let stringNumber = "123"
let number = int(stringNumber)         // 123
let floatNum = float(number)           // 123.0
let backToString = string(floatNum)    // "123.0"

// Safe type conversion
let result = tryInt("abc")             // Option<int>
match result {
    case Some(value) => print("Conversion successful: {value}")
    case None => print("Conversion failed")
}

// Type checking
let value: any = "Hello"
if value is string {
    print("It's a string: {value as string}")
}

✨ Advanced Patterns

Destructuring Assignment

// Array destructuring
let [first, second, ...rest] = [1, 2, 3, 4, 5]
print(first)    // 1
print(rest)     // [3, 4, 5]

// Object destructuring
let { name, age } = user
print("Name: {name}, Age: {age}")

// Destructuring in function parameters
function greet({ name, age }: { name: string, age: int }) {
    print("Hello, {name}! You are {age} years old.")
}

Type Guards

// Custom type guard
function isString(value: any): value is string {
    match value {
        case _: string => true
        case _ => false
    }
}

function safeProcess(value: any) {
    if isString(value) {
        // value is treated as string type here
        print(value.toUpperCase())
    }
}

🚀 Real-world Usage

// Practical type definitions for real projects
type APIResponse<T> = {
    success: boolean,
    data: Option<T>,
    error: Option<string>,
    statusCode: int
}

type User = {
    id: int,
    name: string,
    email: string,
    createdAt: Date
}

// API function definition (automatic async; no manual waiting needed)
function getUser(id: int) -> APIResponse<User> {
    let response = fetch("/api/users/{id}")
    
    if response.ok {
        let userData = response.json()
        return {
            success: true,
            data: Some(userData),
            error: None,
            statusCode: response.status
        }
    } else {
        return {
            success: false,
            data: None,
            error: Some("User not found"),
            statusCode: response.status
        }
    }
}

Topaz's type system provides both safety and expressiveness. Thanks to type inference, you can write concise code while preventing bugs with precise type specifications when needed. 🎯