0

In vscode with typescript

multiple generic not infered properly when to use User-Defined Type Guards

const arraySample = [1, [3, 4], ["s"]];

const isFlat = <T, U>(array: (T | T[] | U | U[])[]): array is (T | U)[] => {
  return !array.some(Array.isArray);
};

if (isFlat(arraySample)) {
  arraySample;
}

vscode tooltip say below with error:

const isFlat: <number, number>(array: (number | number[])[]) => array is number[]

but I think it must be

const isFlat: <number, string>(array: (number | number[] | string | string[])[]) => array is (number|string)[]

could you let me know the proper solution?

1 Answer 1

2

The compiler can't really infer anything meaningful for U in your code, since it won't know where to split up a union. Instead, since conditional types were introduced I'd tend to do it the other way... just let T be the element type of the array and pull out array types from it in the type guard. Like this:

const isFlat = <T>(array: T[]): array is Exclude<T, any[]>[] => {
    return !array.some(Array.isArray);
};

const arr = ["a", 2, true, Math.random() < 0.5 ? "d" : ["d"]];
if (isFlat(arr)) {
    arr; // (string | number | boolean)[]
} else {
    arr; // (string | number | boolean | string[])[]
}

Does that work? Hope that helps; good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.