I'm facing an issue related to Typescript type checking while working with functions. Let's assume I have a Type called IBaseField
and a variable of Type Array<IBaseField>
. When trying to assign a value to this variable, I consistently check for null
and undefined
conditions. Based on the function result, I either assign an empty array or a new value. However, Typescript throws an error stating that Type IBaseField[] | undefined
is not compatible with type IBaseField[]
, even though I have performed the necessary check within the function. Below is the code snippet I attempted:
public constructor(formId:ID, autoFillFields?: Array<IBaseField>) {
this._formId = formId
this._autoFillFields = isNullOrUndefined(autoFillFields) ? [] : autoFillFields
}
Here is the isNullOrUndefined
function used:
export function isNullOrUndefined(obj: any) {
return obj === null || obj === undefined
}
Additionally, the error message displayed by Typescript:
Type 'IBaseField[] | undefined' is not assignable to type 'IBaseField[]'. Type 'undefined' is not assignable to type 'IBaseField[]'.ts(2322)