Issue
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:
Solution
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 ofConstants: Record<string, string>
enables typescript to not only constrain your type toRecord<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;
Answered By - Murolem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.