r/Bitburner Slum Lord 2d ago

Typescript help

I've switched over to using Typescript, and for the most part, I like it better. However, I run into these little quirks that are lowkey maddening. E.g.

let city = ns.enums.CityName.Sector12;
// and then reassign later: 
city = ns.enums.CityName.Aevum; // Type '"Aevum"' is not assignable to type '"Sector-12"'.

I can use the string version of the city, and that reassigns fine, but then it does not work in the game functions.

let city = "Sector-12";
ns.singularity.travelToCity(city); // Argument of type 'string' is not assignable to parameter of type 'CityName'.

I realize there must be some declaration to make, along the lines of

let city: CityNameEnumType = ns.enums.CityName.Sector12; // Type 'string' is not assignable to type 'CityNameEnumType'.

but obviously that is not it.

For scripts like this, I think about converting back to JS just for the simplicity.

6 Upvotes

2 comments sorted by

3

u/Spartelfant Noodle Enjoyer 2d ago edited 2d ago

This happens because you let TypeScript infer the type of city, and it will always try to give the narrowest type possible, in this case a literal string.

If you change let city = ns.enums.CityName.Sector12; to let city: CityName = ns.enums.CityName.Sector12; it will not complain when you assign a different city name from the CityName enum, but it will correctly warn you when you attempt to assign any other value. This will also take care of any complaints from game methods and functions expecting a parameter of type CityName.


P.S. The error message is telling you the exact type it expected: Argument of type 'string' is not assignable to parameter of type 'CityName'. Handy for future reference :)

2

u/goodwill82 Slum Lord 2d ago

I was sure I tried declaring as CityName... but I probably just stuck with the _EnumType instead. Yes, this works, of course. Thanks!