Reputation: 515
I am using typescript and react.js in an asp.net core application. I am getting an error TS property 'Persons' does not exist on type readonly. Can anyone tell me how to overcome this?
export default class HelloWorld extends React.Component<{}, {}> {
constructor(props: any) {
super(props);
this.state = {
persons: [
{ name: 'Max', age: 28 },
{ name: 'Max', age: 28 }
]
}
}
public render() {
return (
<div>
<Person {this.state.persons[0].name} age="28"> My hobbies: racing</Person>
</div>
);
}
import * as React from 'react';
const person = (props: any) => {
return (
<div>
<p> Im {props.name} {props.age}</p>
<p>{props.children}</p>
</div>
)
};
export default person;
Thanks
Upvotes: 1
Views: 311
Reputation: 7976
It looks like you need to mark the type of the array you are assigning to state as readonly.
import * as React from 'react'
interface HelloWorldI {
persons: ReadonlyArray<PersonI>
}
interface PersonI {
name: string,
age: number
}
export default class HelloWorld extends React.Component<{}, HelloWorldI> {
constructor(props) {
super(props)
const p: ReadonlyArray<PersonI> = [
{ name: 'Max', age: 28 },
{ name: 'Max', age: 28 },
]
this.state = {
persons: p,
}
}
public render() {
return (
<div>
<Person name={this.state.persons[0].name}
age= {this.state.persons[0].age}>
My hobbies: racing
</Person>
</div>
)
}
}
class Person extends React.Component<{name: string, age: number}, {}> {
render() {
return( <p>{this.props.name} and {this.props.age}</p> )
}
}
Upvotes: 1