How do I type-check Dictionaries?

  1. What do you want to achieve?

I want to create a structure for my dictionary via type checking.

  1. What is the issue?

The issue is that it does not not raise a type error, despite being strict when the value is not a number.

Types module:

export type _PlayerContainer = {
	[{PlayerName: string}]: {
		
		[{Coins: string}]: number
	}
}

Main script:


local Players:Types._PlayerContainer = {
	["ByGermanKnight"] = {
		
		["Coins"] = "fadsad" <-- Does not raise a type error, 
                              -- despite not being a number
	},
}
2 Likes

I think it would look like something like this

export type _PlayerContainer = {[string] : {
    Coins : number,
    Name : string,
    isAlive : boolean
}}

The issue is that this only type checks the values, but not the index and I want to be able to type check both.

You want to add PlayerName as it’s own type?

He wants to type-check the keys in his dictionary.

@ByGermanKnight I might be wrong because I type-check the values not the keys but I feel like type-checking keys is not possible

1 Like

I have 2 questions:

  1. Are both scripts using strict mode?
  2. Do you have the new Luau type solver beta feature enabled? I tried with it (not without it) and my type checking works fine:
--module

--!strict
export type Type = {
	[string]: {
		["Coins"]: number
	}
}

return "foo"
--script requiring

--!strict
local e = require(script.Parent)

local val: e.Type = {
	["hi"] = {
		["Coins"] = 3
	}
}

No issues:
image

Issue with value:
image

image

Issue with key:

Your type is fundamentally malformed. The correct way to annotate that dictionary is as follows:

-- Private values should not be exported. Declare "PlayerContainer" as a public type by removing the "_" prefix.
export type PlayerContainer = {
    [string]: {
        Coins: number,
    }
}