代码之家  ›  专栏  ›  技术社区  ›  moys

在不使用非null断言或可选链接的情况下消除“Object可能是未定义的”错误

  •  0
  • moys  · 技术社区  · 2 年前

    我有如下代码

    export type ConditionalItemType = [
      { condition: string },
      { [key: string]: FormItemDataType }
    ];
    export type ConditionalItemDataType = ConditionalItemType[];
    
    export type FormItemDataType = {
      required: boolean;
      type: string;
      constraint?: TextConstraintType;
      options?: string[];
      conditional?: ConditionalItemDataType;
    };
    
    export type TextConstraintType = {
      min?: number;
      max?: number;
      format?: string;
    };
    
    const obj: FormItemDataType = {
      required: true,
      type: 'select',
      options: ['simple', 'complicated'],
      conditional: [
        [
          { condition: 'complicated' },
          {
            'How Complicated': {
              required: true,
              type: 'text',
              constraint: {
                max: 30,
              },
            },
          },
        ],
      ],
    };
    
    const func = (input: FormItemDataType) => {
      if ('conditional' in input) {
        input.conditional.filter((arrItem) => console.log(arrItem));
      } else null;
    };
    

    我得到了 'input.conditional' is possibly 'undefined' 错误在 input.conditional.filter((arrItem) => console.log(arrItem))

    如何消除这个错误?我不能使用 non-null assertion optional chaining 。我也不能更改类型。

    我想我可以通过使用“Type Guards”&我想我是在 if ('conditional' in input) 但显然不是。有人能帮忙吗?

    使现代化 enter image description here

    1 回复  |  直到 2 年前
        1
  •  1
  •   Christian    2 年前

    放弃 in 操作员,只需检查 input.conditional 设置,经典的方式。

    const func = (input: FormItemDataType) => {
      if(input.conditional) { // 👈 tells TypeScript that input.conditional under this block must be set
        input.conditional.filter((arrItem) => console.log(arrItem));
      }
    };
    
    推荐文章