我对TypeScript相当陌生,已经收到了一个基于ES6的react项目,并且希望迁移到TypeScript以获得更完整的状态。跟在(这个)之后的任何事情。似乎出现错误(属性"foo“在”bar“类型中不存在)
import * as React from 'react';
import { Component } from 'react';
class Clock extends Component {
constructor(props: {}) {
super(props);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.timerId = setInterval(
() => this.tick(), 500
);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
const options = { hour24: false };
return (
<div className="clockDesign">{this.state.date.toLocaleString('en-US', options)}</div>
);
}
}
export default Clock;我的问题是这个。如何将内联定义转换为类语句中的类型?
发布于 2017-10-24 13:49:22
在分配字段之前,先声明类的字段。例如:
class Clock extends Component {
private state: { date: Date }
constructor(props: {}) {
super(props);
this.state = {
date: new Date()
};
}
// ...
}或者,如果state应该是从Component继承的,那么您的键入(npm install @typings/react)可能会出现一些问题。
发布于 2017-10-24 13:57:05
使用接口 (https://www.typescriptlang.org/docs/handbook/interfaces.html):
interface Props = {
};
interface State = {
date: Date;
}
class Clock extends Component<Props, State> {
private timerId: any;
constructor(props: Props) {
super(props);
this.state = {
date: new Date()
};
}
...
}发布于 2017-10-24 14:00:08
您需要添加正确的泛型参数,并且需要定义类属性。见评论。
进口*作为从“反应”中的反应;
interface IProps { }
interface IState {
date: Date;
}
class Clock extends React.Component<IProps, IState> { //You need to define both props and state
constructor(props: {}) {
super(props);
this.state = {
date: new Date()
};
}
timerId: any; //Props needs to be defined;
componentDidMount() {
this.timerId = setInterval(
() => this.tick(), 500
);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
const options = { hour24: false };
return (
<div className="clockDesign"> {this.state.date.toLocaleString('en-US', options)} </div>
);
}
}
export default Clock;https://stackoverflow.com/questions/46912195
复制相似问题