Hello. For context, I’ve set my scripts as strict.
I’m trying to access a dictionary and set a variable to a table inside that dictionary:
partyService.returnFirstAnatomy = function(entity: string, entityType: string)
type x = {[string]: {}}
local baseAnatomy: x = {} :: x
if entityType == "Party" then
baseAnatomy = entityInfo.partyInformation[entity].Anatomy
elseif entityType == "Enemy" then
baseAnatomy = entityInfo.enemyInformation[entity].Anatomy
end
end
However, on lines: baseAnatomy = entityInfo.partyInformation[entity].Anatomy and baseAnatomy = entityInfo.enemyInformation[entity].Anatomy, I received a type error mentioned in the title of this post. Here are the two modules I’m referencing inside of this script:
you’d access this part by entityInfo.partyInformation.Player
or if your entity == "Player" then entityInfo.partyInformation[entity] would be available
so you mixed up quite a few places here. you checked entityType but you used entity for the index
even if entityType is the correct one, there is only Player . no Party in the table
This doesn’t change anything? They are getting “Player” not “Party” (or Enemy and Stone Golem) from the table, entityInfo.partyInformation[entity] usage is for multiple entities of the same kind as I assume these won’t be the only entities here.
That’s true. Although, I still want to fix this type error in my script and learn how to prevent it from happening again.
You might be misconstruing what I am trying to do. I’m accessing a different table depending on the entityType, and entity exists only to find the exact entity after I know which table to search in.
To reiterate, I am checking if entityType is either "Party" or "Enemy", so the script knows which table to select. entity is the name of the entity itself, which in this instance could be either "Player" or "Stone Golem".
You can’t add an indexer to your module tables because the typechecker is treating their keys as singleton strings. So partyInformation.Player is fine, but partyInformation[str] where str is typed as a string (even if it’s a valid key) is not.
Try to typecast the tables (entityInfo.partyInformation and the other one) into {[string]: EntityInfo} (EntityInfo is the table type containing the Anatomy, Abilities, and everything else) right after where you define them in the module.
If you want to keep Intellisense for the different keys in the table (i.e. have the typechecker acknowledge that the partyInformation table contains the "Player" key) while also keeping it indexable, you’ll have to union the table type with {[string]: never}. I don’t suggest doing this because it’s pretty ugly, and I think the eventual addition of type functions will bring a much cleaner solution.