I’m trying to create an array of objects comprised of a questions, an associated action to perform(a function) and arguments to supply to the function. I don’t understand why typescript cannot understand the type and arguments, I would also like to understand how to achieve such functionality.
playground
type Digit = 0|1|2|3|4|5|6|7|8|9;
const Color = {
red: 0,
black: 1,
} as const;
type Color = typeof Color[keyof typeof Color];
type Code = {
value: Digit,
color: Color
}
function countOfEven(codes: Code[]): number {
return codes.filter((code) => code.value % 2 === 0).length;
}
function countOfColor(codes: Code[], color: Color): number {
return codes.filter((code) => code.color === color).length;
}
let code: Code [] = [
{
value: 1,
color: Color.black
},
{
value: 2,
color: Color.red
}
]
const questions = [
{
body: "How many even numbers?",
action: countOfEven,
},
{
body: "How many red numbers?",
action: countOfColor,
args: Color.red
}]
let question1 = questions.at(0)
let question2 = questions.at(1);
console.log(question1?.body,question1?.action())
console.log(question2?.body,question2?.action(question2.args))