简体   繁体   中英

Typechecking not working for generic string keys in Luau?

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

Unfortunately, in current Luau (0.545 as of this writing in September 2022), once you have an indexer ( [string] ) in your type, the rest of the keys on the type will not be checked in the way you expect.

Using indexers can definitely be a nice ergonomic improvement over explicit method calls, but besides the type system not quite giving the safety you want in those cases, it can sometimes be slower than the explicit method call approach.

When overriding __index, __newindex, and/or __call on tables for better ergonomics, make sure you aren't unknowingly opting out of type safety, or increasing runtime overhead in the hot path of your Luau application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM