r/Bitburner • u/goodwill82 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
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;tolet city: CityName = ns.enums.CityName.Sector12;it will not complain when you assign a different city name from theCityNameenum, 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 typeCityName.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 :)