2

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)

1 Answer 1

5

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

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.