TLDR; I want to be able to set default values for a typechecked table.
For example, This is what I currently use
-- Types
type SettingsType = {
FPS: number?, -- Default: 20
TrackNew: boolean?, -- Default: false
TrackChildren: boolean?, -- Default: true
TrackNewChildren: boolean?, -- Default: true
StaticModels: {Instance}?, -- Default: {}
ActiveModels: {Instance},
}
type SettingsTypeStrict = {
FPS: number,
TrackNew: boolean,
TrackChildren: boolean,
TrackNewChildren: boolean,
StaticModels: {Instance},
ActiveModels: {Instance},
}
local DefaultSettings: SettingsTypeStrict = {
FPS = 20,
TrackNew = false,
TrackChildren = true,
TrackNewChildren = true,
StaticModels = {},
ActiveModels = {}
}
local function NormalizeSettings(Settings: SettingsType): SettingsTypeStrict
local Current: SettingsTypeStrict = DefaultSettings
for Property, _ in pairs(DefaultSettings) do
if Settings[Property] ~= nil then
Current[Property] = Settings[Property]
end
end
return Current
end
I want to make it so if a SettingsType is declared without any of the optional properties (FPS, TrackNew, etc.) a default value is used (currently stored in DefaultSettings). My solution currently involves two seperate types (SettingsType, SettingsTypeStrict), one containing the optional properties, and one where the optional properties are required. I use a function (NormalizeSettings) to convert from the optional type to the strict type.
Anyone have any experience with this? This is my first type messing around with typechecking so I’d love to be able to get a better understanding of it. I’ve looked through the forum and all the typechecking documentation, however, I haven’t had any luck.