Is it possible to inform TypeScript that all potential code paths in a function will return a value?
In my scenario, I provide two numeric arrays as input, verify their monotonically increasing nature, and then retrieve a value based on specific conditions. It seems inevitable that this function will always lead to a defined outcome.
Hence, my inquiry is whether there exists a bug in my implementation, and if not, how can I communicate to TypeScript that every code path (excluding exceptions) guarantees a return value?
const monotonicIncreasing = (array: number[]) => {
for (let i = 0; i < array.length - 1; i++) {
if (array[i+1] < array[i]) {
return false;
}
}
return true;
}
// does not compile (all code paths must return a value)
const foo = (v1: number[], v2: number[], v: number) => {
if (!v1.length || v1.length !== v2.length) {
throw new Error("arrays must have same length");
}
if (!monotonicIncreasing(v1) || !monotonicIncreasing(v2)) {
throw new Error("arrays must be monotonic increasing")
}
if (v <= v1[0]) {
return v2[0];
} else if (v > v1[v1.length-1]) {
return v2[v2.length-1];
} else {
for (let i = 0; i < v1.length-1; i++) {
if (v > v1[i]) {
return v2[i];
}
}
}
}
let a: number;
const arr1 = [1,2,3];
const arr2 = [3,4,5];
a = foo(arr1, arr2, 2);