Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 515
LeO Avatar asked Jan 01 '26 06:01

LeO


1 Answers

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,
                };
            }
like image 59
Matthieu Riegler Avatar answered Jan 05 '26 23:01

Matthieu Riegler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!