pouyan
pouyan

Reputation: 3439

Typescript can not infer undefined or null checking in function

I have an issue with Typescript type checking when I'm using a function. Let say I have a Type IBaseField and I have a variable of Type Array<IBaseField>. When I want to assign a value to this variable I will check for null and undefined and I will assign an empty array or a new value based on the function result. But typescript shows an error that Type IBaseField[] | undefined is not assignable to type IBaseField[] While I have checked it in the function. Here is the code I have tried:

  public constructor(formId:ID, autoFillFields?: Array<IBaseField>) {
    this._formId = formId
    this._autoFillFields = isNullOrUndefined(autoFillFields) ? [] : autoFillFields
  }

and here is my isNullOrUndefined function:

export function isNullOrUndefined(obj: any) {
  return obj === null || obj === undefined
}

and the error shown by typescript:

Type 'IBaseField[] | undefined' is not assignable to type 'IBaseField[]'. Type 'undefined' is not assignable to type 'IBaseField[]'.ts(2322)

Upvotes: 2

Views: 1470

Answers (1)

Tony Coggins
Tony Coggins

Reputation: 78

You need to tell typescript that isNullOrUndefined is a type guard:

export function isNullOrUndefined(obj: any): obj is null | undefined {
  return obj === null || obj === undefined
}

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

Upvotes: 5

Related Questions