Home > Software design >  How to access typescpirt empty object properties
How to access typescpirt empty object properties

Time:08-05

my code is like this

type.js

export interface User {
  name: string;
  age: number;
}

I am using react

Coponent.tsx

const [state,setState] = useState<User|{}>({});

const isValid = () =>{
 const clone = { ...state};
 
 const name:string = clone.name //<= error

}

i tried this

 const name:string = clone?.name

Any good solutions?

CodePudding user response:

User | {} does not mean 'a possibly empty User object.' It means this type is either an object of type User or an empty object. In your React code, you've set the state variable to be an empty object, which will never have the name or age properties.

From the code you've shared, it's hard to deduce what you're trying to accomplish. But depending on what you're trying to do, you could try something like this:

const Component = () => {
  // forget an empty object, use null or undefined (the below expression will set state to undefined)
  const [state, setState] = useState<User | undefined>();

  const isValid = (): boolean => {
    if (!state) {
      return false;
    }
    // now that we know state is not null or undefined, we know it's of type `User`! We can now clone our state for whatever we're trying to do
    const clone = { ...state};
 
    const name:string = clone.name //<= should no longer error
    return true;
  }
}

CodePudding user response:

  const [state, setState] = useState<User | undefined>();

  const isValid = () => {
    if (!state) {
      return false;
    }

    // do validate
    const clone = { ...state };
    const name: string = clone.name;
  };

CodePudding user response:

Please try with this.

const {name} = clone;

  • Related