【发布时间】: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<T, V>' requires 2 type argument(s).。
const result = addId<UserInterface>(user)
console.log('result', result)
我不明白为什么会出现此错误,因为 user 对象具有 name、data 和 meta。
【问题讨论】:
标签: typescript