callable objects with properties

type DescribableFunction = {

  // other properties
  description: string;
  
  (someArg: number): boolean;  // ⭐️ 注意:參數與回傳值之間不是用 => ❗️
//╰─── ⭐️ call signature ───╯
};

function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

比較 callAsFunction in Swift:

struct Dice {

    var lowerBound: Int
    var upperBound: Int

    // ⭐️ callAsFunction
    func callAsFunction() -> Int {
        (lowerBound...upperBound).randomElement()!
    }
}

let d6 = Dice(lowerBound: 1, upperBound: 6)
let roll1 = d6()
print(roll1)

Last updated