简体   繁体   中英

React: Typescript - ignoring Interface on assignment

I have a interface called State defined, and when I set the state in the constructor it is ignoring the interface.

In the constructor I set person which is part of the interface State to the variable somePerson which is not of the interface Person , so it should throw a TypeError but its not


Interfaces:

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;
}

Code:

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
        }
    }
}

Question: why is it allowing me to set state.person to a variable that is not of the type interface Person ?

Typescript can't know if your any variable holds an instance of your object or not. It's anything, so it could be an instance of your object.

Consider this

const x: any = {};

// valid
let y: string = x;

// invalid
y = 1;

let num: any = 1;

// valid
y = num;

Basically you shouldn't be using any in typescript (at least my rule of thumb), because whats the use of typescript in that case? But if you want to use any , then you'll just have to deal with such "weird" scenarios.

Try explicitly settings the state

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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