簡體   English   中英

訪問對象上具有默認值的字段時如何解決流錯誤?

[英]How to fix Flow error when accessing a field with default value on an object?

流REPL

問題

我正在嘗試訪問我認為應該始終存在的對象上的字段。

如何解決以下流錯誤?

片段

problem = (arg: {refKey: string} = {}) => {
  const {refKey = 'ref', ...rest} = arg;
  return {
    [refKey]:arg[refKey],
    ...rest
  };
};

錯誤:

19:       [refKey]:arg[refKey],
                       ^ Cannot get `arg[refKey]` because property `ref` is missing in object type [1].
References:
16:   problem = (arg: {refKey: string} = {}) => {
                      ^ [1]

之所以發生這種情況,是因為您在聲明值時正在設置它。

如果要設置默認值,則可以在默認參數中進行設置,如下所示:

problem = (arg: {refKey: string} = {refKey: 'ref'}) => {
  const {refKey, ...rest} = arg;
  return {
    [refKey]:arg[refKey],
    ...rest
  };
};

編輯

好的,我想我誤解了問題,現在已經理解了(!)。

如果默認屬性將命名為'ref' ,則可以執行以下操作:

problem = (arg: {refKey: string, ref: any} = {}) => {
  const {refKey = 'ref', ...rest} = arg;
  return {
    [refKey]:arg[refKey],
    ...rest
  };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM