Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I enforce typechecking on nested objects with generic keys?

Asked by 2 years ago

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
    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. However, 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? Is there a way for me to enforce typechecking for custom types inside a dictionary for ALL string keys instead of needing to explicitily define them in the type definition? Am I going about this the wrong way?

Any help would be greatly appreciated.

Answer this question