[英]Argument of type 'any[]' is not assignable to parameter of type 'A'. Property 'a' is missing in type 'any[]'
I'm a very beginner in TypeScript and now I'm trying to understand how interfaces works in a Class Method of React Component. 我是TypeScript的初学者,现在我想了解接口在React Component的Class Method中是如何工作的。 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
this._getName(a)
expects a
to be of type A
. this._getName(a)
期望a
的类型为A
A
is defined as an object with a property a
that is of type any[]
. A
被定义为具有属性的对象a
也就是型的any[]
Your call-time a
inside render
is of type []
. 内部
render
调用时间a
[]
类型。
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[]
? 我不确定您要用此代码完成什么,但我想您想说的是
_getName
中的参数a
应该是any[]
类型吗? Then you probably need type A = any[]
. 然后,您可能需要
type A = any[]
。
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) 表示实现接口“ A”的对象必须具有一个名为“ a”的属性,该属性的类型将为“ any []”(任何类型的数组)
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
}
It is necessary to do so: 有必要这样做:
class Test extends Component {
_getName = (a: A) => {
return a.a;
}
render() {
const a = {a: []};
return this._getName(a);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.