【问题标题】:Typescript how to type the rest of parameters in object打字稿如何在对象中键入其余参数
【发布时间】:2021-03-09 04:13:20
【问题描述】:
  function test(data){
      console.log(data)
  }

  test({comments: 'hi', eat: true, sleep: true})

在测试函数中,我确定会出现comment参数,而对于其他参数,属性可能是动态的,但值是布尔类型的,

  test({comments: 'hi', drink: true, sleep: true})

考虑到这种情况,我应该如何正确输入数据? 我尝试过类似的方法,但似乎不对

function(data: {data: {comments: string, [key: string]: boolean})

【问题讨论】:

  • 是的。我只是想安慰。编辑了问题
  • 然后是问题,“我给参数data 赋予什么类型,它应该是一个对象,它至少有一个名为comments 的字符串类型的属性,但它可能有很多我不关心的其他属性”?
  • 是的..我不关心其他属性..
  • 如果您不关心其他属性,那么type DataType = { comments: string; [key: string]: unknown; }; 将起作用。参考:stackoverflow.com/a/33860616
  • 对,对,你的问题确实不同(而且很酷)。看起来十字路口类型有潜力,但不足。更多信息在这里:github.com/microsoft/TypeScript/issues/20597.

标签: javascript typescript


【解决方案1】:

我可以建议你一些解决方法:

function test<T extends {
  [key: string]: any;
}>(data: { comments: unknown } & { [key in keyof T]: key extends "comments" ? string : boolean }) {
  const comments = data.comments as string;
  console.log(comments);
  console.log(data.eat);
  console.log(data.sleep);
}

test({comments: "hi"}); // works
test({comments: "hi", eat: true}); // works
test({comments: true}); // doesn't works
test({comments: 5}); // doesn't works
test({comments: "hi", eat: "true"}); // doesn't works
test({comments: "hi", eat: 5}); // doesn't works

它在函数体之外很好地输入,但在函数体中正确输入data.comments,您应该添加一些缩小范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2019-10-18
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多