3

I have an enum file Themes.ts

export enum Themes {
    DEFAULT = 'default',
    DARK = 'dark'
}

And I want to use that enum as a default prop in a <Test/> component that looks like

export type TestProps = {
    children: ReactChild,
    theme?: Themes,
}

export const Test = ({ children, theme = Themes.DEFAULT }: TestProps) => {
    console.log(theme)
    return (
        <div className={`${theme}`}>
            <div>
                { children }
            </div>
        </div>
    )
}

The issue i'm seeing is that console.log(theme) is printing Themes.DEFAULT instead of default so the default value isn't being set properly. Is there anyway to use an enum to set this default theme value so that it will evaluate properly?

EDIT : What ended up working was setting a const to the enum values and then passing that into the props

const enumValue = Themes.DEFAULT
export const Test = ({ children, theme = enumValue }: TestProps) => {

2 Answers 2

5

Use string union types instead of enums. This way you keep the same type strength and your strings can be strings.

export type Themes = 'default' | 'dark';

Then in your component

export type TestProps = {
    children: ReactChild,
    theme?: Themes,
}

export const Test = ({ children, theme = 'default' }: TestProps) => {
    console.log(theme)
    return (
        <div className={`${theme}`}>
            <div>
                { children }
            </div>
        </div>
    )
}

If you try to assign anything besides 'default' or 'dark', the TS compiler will throw an error.

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

2 Comments

This was useful, but not quite what I was looking for. Wanted to avoid hardcoding strings in code
It may look like it's just hard coding a string. But it's assigning one of two possible values accepted by this type. Just like your would if using enums.
1

Everything looks right. I tried to reproduce it but everything works fine https://codesandbox.io/s/interesting-spence-kw3og?file=/src/App.tsx

1 Comment

The same issue is happening with me. If I pass a ENUM as parameter, works. But, when the component uses the default value, not works, the error reported on this question happens.

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.