I am learning Typescript and I got this error Generic type 'BallInterface' requires 2 type argument(s)
at tennisBall. How can I call the function whose parameter object has more than one generic type? Why is it throwing an error? The whole code:
const addId = <T extends object>(obj: T) =>{
const id = 3;
return {
...obj,
id
}
}
interface BallInterface<T, V>{
name: string
data: T
meta: V
}
const ball: BallInterface<{meta: string}, string> = {
name: "Tennis",
data:{meta: "for playing"},
meta: "Mario"
}
const tennisBall = addId<BallInterface>(ball);
It is throwing an error because you defined BallInterface
as an interface that has two generics.
On the last line, you call addId
you pass BallInterface
as generic, without specifying what would T
and V
of BallInterface be.
It's not entirely clear what your goal is here. If all you want to achieve is to add the Id
field, you don't need to pass a generic to addId
at all. You're making it more difficult than what actually is :)
const addId = (obj: object) =>{
const id = 3;
return {
...obj,
id
}
}
interface BallInterface<T, V>{
name: string
data: T
meta: V
}
const ball: BallInterface<{meta: string}, string> = {
name: "Tennis",
data:{meta: "for playing"},
meta: "Mario"
}
const tennisBall = addId(ball);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.