[英]React: Typescript - ignoring Interface on assignment
我定义了一个名为State
的interface
,当我在constructor
设置状态时,它忽略了该接口。
在constructor
我将作为interface State
一部分的person
设置为不属于interface Person
的变量somePerson
,因此它应该抛出一个TypeError
但它不是
接口:
interface Person{
id: number;
name: string;
phone: string;
email: string;
photo: string;
position: string;
}
interface Test {
workday: any;
person: Person;
}
interface Props {
data: Test;
settings: any;
}
interface State{
person: Person;
contract: number;
manager: Manager;
workday: Workday;
}
代码:
export class MyComponent extends Component<Props,State> {
constructor(props: Props){
super(props);
// destructuring from the @props
// this [person] is not of the interface type Person
let { person: somePerson } = this.props.data;
this.state = {
...this.state,
person: somePerson // not of type Person
}
}
}
问题:为什么它允许我将state.person
设置为不是interface Person
类型的变量?
Typescript 无法知道您的any
变量是否包含您的对象的实例。 它是任何东西,所以它可以是你的对象的一个实例。
考虑这个
const x: any = {};
// valid
let y: string = x;
// invalid
y = 1;
let num: any = 1;
// valid
y = num;
基本上你不应该在打字稿中使用any
(至少我的经验法则),因为在这种情况下打字稿的用途是什么? 但是如果你想使用any
,那么你只需要处理这种“奇怪”的场景。
尝试明确设置状态
export class MyComponent extends Component<Props,State> {
state: State;
constructor(props: Props){
super(props);
// destructuring from the @props
// this [person] is not of the interface type Person
let { person: somePerson } = this.props.data;
this.state = {
...this.state,
person: somePerson // not of type Person
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.