0

I'm continuing to read the Adam Freeman book on angular but again stuck with the example around form validation using FormGroup, as presume it used to work but now 2 versions on typescript doesn't like it.

I can see what it is trying to do, after clicking the submit button it gets each form value and assigns them back onto my Product object. hence using the index ['name'] type approach. If I actually put the value of 'name', 'category' or 'price' in the place of c against this.newProduct, it works fine but then I also need the other two values to be updated.

Object.keys(this.formGroup.controls)
    .forEach(c => this.newProduct[c] = this.formGroup.controls[c].value)

My product object looks like this

export class Product {
    constructor(public id?: number,
    public name?: string,
    public category?: string,
    public price?: number) {}
}

enter image description here

How can I make this work in an understandable way?

I have found this link but I cant seem to fathom if I can use it or not.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

The approach documented in the book does feel overly complex and clunky, just give me some C# :)

1 Answer 1

1

Object.keys returns an array of strings. This is intentional, as mentioned in this issue, for example.

Types in TS are open ended. So keysof will likely be less than all properties you would get at runtime.

If you know what you're doing, you can do an explicit cast (more formally, a type assertion) to a narrow type which Product will accept as an index:

const keys = Object.keys(this.formGroup.controls) as Array<keyof Product>
keys.forEach(c => this.newProduct[c] = this.formGroup.controls[c].value)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thank you, yes I dont know what I am doing just yet! something like that comes along and I'm stumped. Thanks for the great help, really appreciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.