Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string' is not assignable to type 'number' as required for computed enum member values

I am getting an error as Type 'string' is not assignable to type 'number' as required for computed enum member values. when I use conditional string with typescript enum operator.

here is the code :

export enum Constants {
  PRODUCTS_URL = "/api/products",
  BASE_URL = process.env.NODE_ENV === "development" ? "http://localhost:8080" : "",
}

following the answer from Muroleum, getting this issue:

issue

like image 271
user2024080 Avatar asked Oct 27 '25 14:10

user2024080


1 Answers

This or similar issue with enums appears to be fixed, but the error persists nevertheless.

How about using an object instead of an enum? With these changes, it behaves similarly with some additional benefits:

  • Record<string, string> type allows defining a string key-string value object.
  • Readonly modifier permits only reading, not writing.
  • Using satisfies Record<string, string> instead of Constants: Record<string, string> enables typescript to not only constrain your type to Record<string, string>, but further narrow it using keys and values you defined, allowing you to reference individual properties with autosuggest and get errors when trying to access non-existing properties.
export const Constants = {
    PRODUCTS_URL: "/api/products",
    BASE_URL: process.env.NODE_ENV === "development" ? "http://localhost:8080" : "",
} satisfies Readonly<Record<string, string>>;

// ok
let v1 = Constants.BASE_URL;

// error, property foo is not defined
let v2 = Constants.foo;
like image 157
Aliser Avatar answered Oct 29 '25 05:10

Aliser