W
W
Wasya UK2019-12-04 16:57:32
JavaScript
Wasya UK, 2019-12-04 16:57:32

Why can't assign values ​​via for in in typescript?

What's the right way to do things like this?

constructor(recipeDetails: { title?: string, description?: string } = { title: "", description: "" }) {
    for (let key in recipeDetails) {
      this[key.toString()] = recipeDetails[key];
    }
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wasya UK, 2019-12-04
@dmc1989

constructor(recipeDetails: Details = { title: "", description: "", ingredients: [] }) {
    for (let key in recipeDetails) {
      (this[key as keyof Details] as Details[keyof Details]) = recipeDetails[key as keyof Details];
    }
  }

 interface Details { title?: string, description?: string, ingredients?: RecipeIngredient[]}

0
0xD34F, 2019-12-04
@0xD34F

Why such difficulties? Enough . Object.assign(this, recipeDetails)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question