0

I have the following formgroup:

this.formBuilder.group<{
    id: number;
    nameDe?: FormControl<string>;
    nameFr?: FormControl<string>;
    nameIt?: FormControl<string>;
}>({
    id: value?.id || null
});

Focus is on the "nameXY" fields. These are added dynamically/based on conditions.

languages.forEach((lang) => { // languages can be ['De', 'Fr'] or ['Fr', 'It']
    const nameIdentifier = 'name' + lang;
    formGroup.addControl(nameIdentifier, new FormControl<string>(value?.[nameIdentifier] || '', Validators.required));
});

Now I get this error:

Argument of type 'string' is not assignable to parameter of type ...

Obviously it's because nameIdentifier is only a string and not 'nameDe' | 'nameFr'| 'nameIt'.

The first approach I tried was to explicitely define the type for nameIdentifier:

const nameIdentifier: 'nameDe' | 'nameFr' | 'nameIt' = 'name' + lang;

Then I get this error:

Type 'string' is not assignable to type '"nameDe" | "nameFr" | "nameIt"'.ts(2322)

Now I'm out of ideas. :) Are there any clean approaches without having to use tons of explicit typing?

1 Answer 1

1

Try type assertion using as keyword.

const nameIdentifier = ('name' + lang) as 'nameDe' | 'nameFr' | 'nameIt';

Or

you can use FormRecord

Sign up to request clarification or add additional context in comments.

2 Comments

This "mutes" the error but doesn't add to type safety, right?
Yes for dynamic field it is index typed.

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.