0

I have the following code, i'm using Typescript:

interface User {
  email: string
  password: string
}

const user : User = {
  email: 'foo@bar.com',
  password: 'foo'
}

for (let prop in user) {
  // how to get key and value destructuring
}

How do I get the property and the value of my object in two variables?

Diego Lope Loyola
  • 781
  • 2
  • 9
  • 15

2 Answers2

0

If you want to loop over the properties and print each, a solution that worked for me on the TS playground is using Object.entries():


interface User {
  email: string
  password: string
}

const user : User = {
  email: 'foo@bar.com',
  password: 'foo'
}

for (let [k, v] of Object.entries(user)) {
    console.log("property " + k + " is ")
    console.log(v);
}

Not quite sure what you mean with null values, since you can't assign null to those properties (tsc will error). If the data is from somewhere else you can always compare each to null in that loop.

atultw
  • 921
  • 7
  • 15
0

You can do this:

for (const prop in user) {
    const tmpProp = prop as keyof User
    console.log(user[tmpProp])
}

also if I suggest you to do this, which is simpler:

Object.keys(user).forEach(key => console.log(key))
InsalataCondita
  • 301
  • 1
  • 6