Consider this scenario with a basic parser:
const str = "String to test";
let pos = 0;
function eat(
...args: (
| [RegExp, (result: RegExpExecArray) => boolean]
| [string, (result: string) => boolean]
| [string[], (result: number) => boolean]
)[]
) {
const oldPos = pos;
for (const [test, callback] of args) {
if (test instanceof RegExp) {
test.lastIndex = pos;
const match = test.exec(str);
if (match) {
pos = test.lastIndex;
if (callback(match)) return true;
break;
}
} else if (typeof test === "string") {
if (str.substr(pos, test.length) === test) {
pos += test.length;
if (callback(test)) return true;
break;
}
} else {
const temp = test.findIndex(item => str.substr(pos, item.length) === item);
if (temp != -1) {
pos += test[temp].length;
if (callback(temp)) return true;
break;
}
}
}
pos = oldPos;
return false;
}
if (eat(
[/string/iy, result /* RegExpExecArray */ => {
// ...
return true;
}],
[["foo", "bar"], result /* number */ => {
// ...
return true;
}]
)) console.log("Matched");
However, this method may be cumbersome when making a call. It also doesn't seem to work in my specific case. I've experimented with generics and function overloads, but they either do not work or do not meet my requirements (especially because I mix different types of argument arrays when calling the function). Any suggestions on how to address this issue? Should I consider raising it on GitHub's issue page if it appears to be a bug? You can find additional experiments related to this problem in this typescript playground.function example(arg: ["string", string, number] | ["boolean", boolean, bigint]) {
if (arg[0] === "string") {
Math.floor(arg[2]); // satisfies the compiler
}
}