Home > other >  how to tell TS compiler that returned value is not null via custom function
how to tell TS compiler that returned value is not null via custom function

Time:08-10

not sure if this is available in TS but i am willing to bet there is a way to make this work.

this code:


const someArray: foo[] | null | undefined = [...]

// TS fail: someArray possibly undefined
<MyComponent data={someArray} /> 


// TS OK
if (someArray) return <MyComponent data={someArray} />


// TS fail: someArray possibly undefined
if (any(someArray)) return <MyComponent data={someArray} />

my func:

export function any(arr: any[] | null | undefined): boolean {
  if (arr && arr.length > 0) {
    return true
  }
  return false
}

question: is it possible to construct any() (maybe using generic hints) to signal to TS that the checked array is not null/undefined?

CodePudding user response:

You're looking for a "type predicate" / type guard.

You can use the is keyword in a function return value to cast the type of the argument in the positive condition.

export function any<T>(arr: any[] | null | undefined): arr is T[] {
  if (arr && arr.length > 0) {
    return true  // if func returns true, then the arg is of type T[]
  }
  return false
}
  • Related