繁体   English   中英

反应:打字稿 - 在分配时忽略接口

[英]React: Typescript - ignoring Interface on assignment

我定义了一个名为Stateinterface ,当我在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM