Home > Enterprise >  type narrowing in ternary
type narrowing in ternary

Time:01-21

In myFunction below, I accept a parameter which is either a string or an array of strings, and I normalize it to an array in the function body:

export const myFunction = <T extends string | string[]>(
  myParam: T
) => {
  let myStringArray = (Array.isArray(myParam) ? myParam : [myParam])
}

I expected Array.isArray to narrow the type in the branches of the ternary operator to either string or string[] so that the final type of myStringArray would be string[]. Instead, the final type is more complicated: (T & any[]) | T[].

enter image description here enter image description here enter image description here

This has been previously reported as marked as working as intended: https://github.com/microsoft/TypeScript/issues/39550

  • Related