Rook
РусскийRU

Generics

Type parameters go in angle brackets, with a constraint after each, as in Go: func last<T any>(xs T[]) ?T, interface Box<T>, class Stack<T>. Type arguments are in angle brackets too: Box<number>, Stack<string>. A generic task collection or store can retain the task type as values pass through it, while the same collection logic can be reused for other types.

The compiler infers the type arguments of a call from the arguments or from the expected type; a call may also give them, fill<Song>(2). The constraint <T Named> allows only fitting types and gives values of type T the members of Named. In JS the types are erased.

// The type parameter T: the function works with an array of any values and knows the result type
func last<T any>(xs T[]) ?T {
    return xs.length > 0 ? xs[xs.length - 1] : null
}

const fruit = last(["guava", "lychee"])  // ?string
const count = last([1, 2, 3])            // ?number

// A constraint: T fits Named, so x has a name
interface Named {
    name string
}

func names<T Named>(items T[]) string {
    return items.map(x => x.name).join(", ")
}

// A generic class; the type argument comes from the variable's declaration
class Stack<T> {
    private items T[]

    push(item T) {
        this.items.push(item)
    }

    pop() ?T {
        return this.items.pop() ?? null
    }
}

let stack Stack<string> = new Stack()
stack.push("papaya")
console.log(fruit, count, names([{ name: "Ann", age: 30 }]), stack.pop())
// stack.push(1) is a compile error: a string is needed

A generic function may make a value of its type, make(T), or check a value against it, decode<T>: T then comes from each call (make).