Home > Software engineering >  Typescript not respecting components defaultProps
Typescript not respecting components defaultProps

Time:04-07

I'm having trouble figuring out what's going wrong here:

export type PackageLanguage = "de" | "en";
export interface ICookieConsentProps {
    language?: PackageLanguage ;
}

function CookieConsent({ language }: ICookieConsentProps) {
    useEffect(() => {
        LanguageHelper.setLanguageFile(language || "en"); <--- PROBLEM HERE !
    }, [language]);

    return <div className="cc__gimme-cookies"></div>;
}

CookieConsent.defaultProps = {
    language: "en",
} as Partial<ICookieConsentProps>;

I'd like to use the language property in some function. Why does TypeScript ignore the defaultProps I've set for the language prop and want's me to check for undefined?

LanguageHelper.setLanguageFile(language); Argument of type 'PackageLanguage | undefined' is not assignable to parameter of type 'PackageLanguage'. Type 'undefined' is not assignable to type 'PackageLanguage'.ts(2345)

LanguageHelper.setLanguageFile(language || "en"); This works fine but is kinda redundant, since I defined defaultProps.

Thanks for any advice in advance!

Kind Regards, Andreas | asdf1414

CodePudding user response:

Because language is typed as optional so conceivably could be undefined.

You could look at combining Pick and Required utility functions to get the result you need.

export type PackageLanguage = "de" | "en";
export interface ICookieConsentProps {
    language?: PackageLanguage;
    otherProp: string;
    propNotInterestedIn: string;
}

type Props = Pick<ICookieConsentProps, 'language' | 'otherProp'>

function CookieConsent({ language }: Required<Props>) {
    useEffect(() => {
        LanguageHelper.setLanguageFile(language || "en"); <--- PROBLEM HERE !
    }, [language]);

    return <div className="cc__gimme-cookies"></div>;
}

CookieConsent.defaultProps = {
    language: "en",
    otherProp: "another prop"
} as Required<Props>;

  • Related