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

返回TypeScript接口成员问题

  •  0
  • tesicg  · 技术社区  · 5 年前

    代码如下所示:

    接口.ts:

    export interface UnitFound {
      payment_message: string;
    }
    

    <script lang="ts">
    import { UnitFound } from "@/Interfaces";
    
    export default defineComponent({
      ...
      computed: {
        PaymentMessage() {
          const found: UnitFound = this.units.find((element: any) => element.id === this.selectedUnitId);
          return found.payment_message;
        }
      },
      ...
    });
    </script>
    

    我收到错误信息:

    "TypeError: Cannot read property 'payment_message' of undefined"
    

    我做错了什么?

    1 回复  |  直到 5 年前
        1
  •  0
  •   tony19 thanksd    5 年前

    this.units.find() can return undefined 如果找不到匹配项,则可能发生以下情况:

    • this.units 最初为空
    • 不为空,但不包含具有 id 匹配的 this.selectedUnitId

    您可以使用 optional chaining

    export default defineComponent({
      computed: {
        PaymentMessage() {
          const found: UnitFound = this.units.find(/*...*/);
          return found?.payment_message || '';
        }             👆
      },
    })
    
    推荐文章