Typescript Enum Alternative

04 Jan 2025

Using Enum

    enum LoginMode {
        email= 'email',
        social= 'social'
    };

    function initiateLogin(mode: LoginMode) {
        //..
    }

    initiateLogin(LoginMode.email); // OK

    initiateLogin('social'); // Error: Argument of type 'string' is not assignable to parameter of type 'LoginMode'.

Using Type (Enum Alternative)

    const LoginMode = {
        email: 'email',
        social: 'social',
    };

    type LoginMode = typeof LoginMode[keyof typeof LoginMode];

    function initiateLogin(mode: LoginMode) {
        //..
    }

    initiateLogin(LoginMode.email); // OK
    
    initiateLogin('social'); // OK