Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular – strict: Type unions

I have defined the following types

export interface LanguageEditInfoDto {
    canEdit: boolean;
    label: string;
    useDudenLang: boolean;
}
export type UILanguageEditInfoDto = LanguageEditInfoDto & {
    isFormValid: boolean;
};

and I have defined the following function:

function setLanguages(languages: Record<string, LanguageEditInfoDto>) {
    const langState: Record<string, UILanguageEditInfoDto> = {};
    for (const langCode in languages) {
        langState[langCode] = {
            isFormValid: true,
            ...languages[langCode],
        };
    }
}

Why do I get the following error for langState[langCode]? AND how to resolve it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TS2322: Type
{   canEdit?: boolean | undefined;   label?: string | undefined;   useDudenLang?: boolean | undefined;   isFormValid: true; }
is not assignable to type UILanguageEditInfoDto
Type
{   canEdit?: boolean | undefined;   label?: string | undefined;   useDudenLang?: boolean | undefined;   isFormValid: true; }
is not assignable to type LanguageEditInfoDto                   

According to the definition none of the attributes are optional. Therefore the assertion is IMHO wrong.

>Solution :

You have noUncheckedIndexedAccess enabled in your project.
You can fix your issue by asserting non null :

    langState[langCode] = {
                    isFormValid: true,
                    ...languages[langCode]!, // here
                };
            }

Or you could keep typesafty by using Object.entries

for (const [langCode, language] of Object.entries(languages)) {
    langState[langCode] = {
                    isFormValid: true,
                    ...language,
                };
            }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading