Reputation: 1318
I'm a very beginner in TypeScript and now I'm trying to understand how interfaces works in a Class Method of React Component. I created a simple case for it, but it does not work. I always gets an error like in this post title.
I'll be pleased for any help.
import React, { Component } from 'react'
interface A {
a: any[]
}
class Test extends Component {
_getName = (a: A) => {
return a
}
render() {
const a = []
return (
<div>{this._getName(a)}</div>
)
}
}
export default Test
Upvotes: 0
Views: 888
Reputation: 838
It is necessary to do so:
class Test extends Component {
_getName = (a: A) => {
return a.a;
}
render() {
const a = {a: []};
return this._getName(a);
}
}
Upvotes: 1
Reputation: 3000
interface A {
a: any[]
}
means that the object that implements the interface "A" is required to have a property called "a" that will be of type "any[]" (array of any type)
but here:
const a = []
it looks like a is just an empty array - not an object, thus not having properties
In my opinion you don't need an interface here. Try instead:
_getName = (a: any[]) => {
return a
}
Upvotes: 1
Reputation: 10153
this._getName(a)
expects a
to be of type A
. A
is defined as an object with a property a
that is of type any[]
. Your call-time a
inside render
is of type []
.
I'm not sure what it is you are trying to accomplish with this code but I guess what you want is to say that the parameter a
in _getName
should be of type any[]
? Then you probably need type A = any[]
.
Upvotes: 1