简体   繁体   English

Typescript 无法推断未定义或 null 检查 function

[英]Typescript can not infer undefined or null checking in function

I have an issue with Typescript type checking when I'm using a function.当我使用 function 时,我遇到了 Typescript 类型检查的问题。 Let say I have a Type IBaseField and I have a variable of Type Array<IBaseField> .假设我有一个IBaseField类型,并且我有一个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.当我想为这个变量分配一个值时,我将检查nullundefined ,我将根据 function 结果分配一个空数组或一个新值。 But typescript shows an error that Type IBaseField[] | undefined但是 typescript 显示错误类型IBaseField[] | undefined IBaseField[] | undefined is not assignable to type IBaseField[] While I have checked it in the function. IBaseField[] | undefined不能分配给类型IBaseField[]虽然我在 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:这是我的isNullOrUndefined function:

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

and the error shown by typescript:以及 typescript 显示的错误:

Type 'IBaseField[] |输入'IBaseField[] | undefined' is not assignable to type 'IBaseField[]'. undefined' 不可分配给类型 'IBaseField[]'。 Type 'undefined' is not assignable to type 'IBaseField[]'.ts(2322)类型“未定义”不可分配给类型“IBaseField[]”.ts(2322)

You need to tell typescript that isNullOrUndefined is a type guard:你需要告诉 typescript isNullOrUndefined是一个类型保护:

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 https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM