【问题标题】:Why does the function requires two arguments if it already has them inside an object?为什么函数需要两个参数,如果它已经在一个对象中?
【发布时间】:2021-07-13 02:27:14
【问题描述】:

我目前正在学习 Typescript,但遇到了一个对我来说不太有意义的错误。

下面的函数addId有一个对象作为参数

const addId = <T extends object>(obj: T) => {
  const id = Math.random().toString(16)
  return {
    ...obj,
    id,
  }
}

还有一个interface,它有两种泛型。

interface UserInterface<T, V> {
  name: string;
  data: T;
  meta: V;
}

现在,我创建一个名为 user 的对象,它接受一个对象和一个字符串。

const user: UserInterface<{ meta: string }, string> = {
  name: 'Jack',
  data: {
    meta: 'foo',
  },
  meta: 'bar'
}

当我调用函数addId 时,它会抛出以下错误:Generic type 'UserInterface&lt;T, V&gt;' requires 2 type argument(s).

const result = addId<UserInterface>(user)
console.log('result', result)

我不明白为什么会出现此错误,因为 user 对象具有 namedatameta

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我不太清楚你想通过上面的用户声明来实现什么? 但在我看来,您的问题在于&lt;UserInterface&gt;(user),编译器期望接口有两个参数! 为什么不implement the interface through a class and create a user object using that class

    更新:

    尝试像这样调用:const result = addId(user) 而不是 const result = addId(&lt;UserInterface&gt;(user))

    【讨论】:

    • 谢谢,我会调查的。我只是关注the example from this video,但似乎该示例在“现实世界”中可能没有意义。
    • 好的。尝试像这样拨打电话:const result = addId(user) 而不是 const result = addId(&lt;UserInterface&gt;(user))
    猜你喜欢
    • 2013-02-21
    • 2021-06-29
    • 2019-03-11
    • 1970-01-01
    • 2020-10-01
    • 2017-10-06
    • 1970-01-01
    • 2018-02-18
    • 2018-02-27
    相关资源
    最近更新 更多