I am currently working on creating an array of objects that consist of questions, associated actions to perform (functions), and arguments to supply to the functions. I am facing issues with TypeScript not recognizing the types and arguments, and I would like to learn how to tackle this problem effectively.
Although my code is functioning as expected and returning the desired results, TypeScript seems to be unhappy...
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(code)) // error!
// ~~~~~~
// Expected 2 arguments, but got 1.
console.log(question2?.body, question2?.action(code, question2.args)) // error!
// ~~~~~~~~~~~~~~
// Argument of type '0 | undefined' is not assignable to parameter of type 'Color'.
// Type 'undefined' is not assignable to type 'Color'.