I'm trying to create a dictionary data structure that contains several CustomType objects that can be associated with any string key.
I figured I could just use {[string]: CustomType} as my dictionary type, like this:
--!strict
type CustomType = {
a: string,
b: string
}
local dictionary: {[string]: CustomType} = {
keyOne = { a = 'hello' }, -- should display type error ('b' field missing)
keyTwo = { a = 'hello', b = 'world'} -- should be fine
}
However, in the code snippet above no type error is shown in the code editor even though the b field is missing from keyOne. Yet, if I explicitly define the keys in the dictionary type definition, then it works as expected:
--!strict
type CustomType = {
a: string,
b: string
}
local dictionary: {keyOne: CustomType, keyTwo: CustomType} = {
keyOne = { a = 'hello' }, -- displays type error
keyTwo = { a = 'hello', b = 'world'} -- is fine
}
Why is this? I would like to enforce strict typechecking for all generic string keys without needing to explicitly define them in the dictionary type definition. Am I going about this the wrong way? Could this be a ROBLOX issue (since I am implementing this in the ROBLOX engine)?
Any help would be greatly appreciated.
Source/info about Luau typechecking: https://luau-lang.org/typecheck
keyOnebeing considered differently combined with duck typing. Could you try using the value key syntax and a string literal? Like["key"] = value?['keyOne'] = { a = 'hello' }but it doesn't seem to make any difference.b, give it a value likenil,1ortrue; and it displays a type error. Using a variable makes it work normally. This could be a bug.