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

react typescript: use "Object.freeze" (enum) as type

I have this "enum":

export const AuthEnum = Object.freeze({
      AUTHENTICATED: 1,
    UNAUTHENTICATED: 2,
    PENDING: 3
})

This would work but is kind of misleading:

const [isAuthenticated, setIsAuthenticated] = useState<number>(AuthEnum.PENDING);

This is what I would like to do, but which doesn’t work:

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

const [isAuthenticated, setIsAuthenticated] = useState<AuthEnum>(AuthEnum.PENDING);

This doesn’t work either:

const [isAuthenticated, setIsAuthenticated] = useState<typeof AuthEnum>(AuthEnum.PENDING);

Is it possible to somehow indicate that the type of the state is AuthEnum?

>Solution :

This useState<AuthEnum>(AuthEnum.PENDING) does not work because AuthEnum is a runtime value and it is used as a type. It might be allowed to use in this way only if AuthEnum would be an enum.

This const [isAuthenticated, setIsAuthenticated] = useState<typeof AuthEnum>(AuthEnum.PENDING); does not work because typeof AuthEnum is an object and you are passing a AuthEnum.PENDING which is a number.

In fact, you want to use only values of AuthEnum. In order to do that, first of all you should use as const assertion to narrow the type of object values.

import React, { useState } from 'react'

const FakeEnum = {
    AUTHENTICATED: 1,
    UNAUTHENTICATED: 2,
    PENDING: 3
} as const // immutability assertion

export const AuthEnum = Object.freeze(FakeEnum)

type Values<T> = T[keyof T]

const App = () => {
    const [isAuthenticated, setIsAuthenticated] = useState<Values<typeof AuthEnum>>(AuthEnum.PENDING);

    setIsAuthenticated(1) // ok
    setIsAuthenticated(2) // ok
    setIsAuthenticated(3) // ok
    setIsAuthenticated(4) // expected error

    return null
}

Playground

Values utility type return a union of all object values.

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