【问题标题】:How to use optional object members?如何使用可选对象成员?
【发布时间】:2021-10-31 13:01:02
【问题描述】:

我有一个对象总是有两个成员,在某些情况下,可以添加第三个。

尝试 #1:可选成员

let initObject = {
    headers: headers,
    method: method ? 'GET' : method,
    body?: ''
  }
  if (method === 'POST') {
    initObject.body = body
  }

TS1162: An object member cannot be declared optional. 失败

尝试#2:强制添加成员:

let initObject = {
    headers: headers,
    method: method ? 'GET' : method,
  }
if (method === 'POST') {
    initObject.body = body
  }

这会失败,TS2339: Property 'body' does not exist on type '{ headers: Headers; method: string; }'.

如何向对象添加可选成员?

我目前使用一种解决方法,但它是重复的,我相信有更好的方法

let initObject
if (method === 'GET') {
    initObject = {
      headers: headers,
      method: 'GET',
    }
  } else if (method === 'POST') {
    initObject = {
      headers: headers,
      method: 'POST',
      body: body
    }
  }

【问题讨论】:

    标签: typescript javascript-objects


    【解决方案1】:

    分别使用对象类型interface(您仍然需要正确设置类型):

    对象类型中的每个属性都可以指定几件事: 类型,属性是否可选,属性是否可以 被写入。

    interface InitObject {
      headers: any;
      method: any; // e.g. 'GET' | 'POST'
      body?: any; // body is optional
    }
    
    let initObject: InitObject;
    
    ...
    
    if (method === 'GET') {
      initObject = {
        headers: headers,
        method: 'GET'
      };
    } else if (method === 'POST') {
      initObject = {
        headers: headers,
        method: 'POST',
        body: body
      };
    }
    

    编辑:这也可以通过使用接口来工作:

    let initObject: InitObject = {
      headers: headers,
      method: method ? 'GET' : method
    };
    
    if (method === 'POST') { // or maybe initObject.method === 'POST'
      initObject.body = body;
    }
    

    【讨论】:

    • 我不确定这会为我的解决方法增加什么?我期待一种避免重复代码的方法(= 如果满足条件,只需更新对象)。
    • @WoJ 查看我的更新。我希望它有帮助:)
    【解决方案2】:

    我认为@pzaenger 的答案是最好的解决方案,但如果您不想使用界面,可以使用:

    const initObject = {
        headers,
        method: method || 'GET',
        body: method === 'POST' ? body : undefined
    }
    

    你对method 使用的三元条件对我来说也没有意义

    【讨论】:

    • 三元应该表示“如果method 是真值,则使用该值,否则使用'GET'”。现在:i) 我意识到我把它弄反了,ii) 我切换到包含函数的参数的默认值(method 是参数)
    • 啊,制作 body undefined 的好主意 - 这实际上解决了我的问题(这是 TS 不接受 GET 操作的主体)
    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2022-01-16
    • 2015-01-07
    • 2013-05-12
    • 2015-07-10
    • 2013-11-28
    相关资源
    最近更新 更多