Typing issue with a custom generic function

I’m learning to work with the type solver and attempting to create a filter function to filter table types. However, I’m getting type system errors and can’t grasp how to properly implement this approach.

--!strict

type function filter(t: type, m: type)
 if not (t:is("table") and m:is("function")) then
  error("nah")
 end
 
 local filtered = nil
 
 for k, v in t:properties() do
  if not m:returns().tail then continue end
  
  if filtered then
   filtered = types.intersectionof(filtered, 
    types.newtable({k = v}))
  else
   filtered = types.newtable({k = v})
  end
 end
 
 return if filtered then filtered else types.singleton(nil)
end

type function sorter(k: type, v: type)
 return types.singleton(k:value() == "oliver")
end

local a = {
 jason = 12.5,
 jack = "roblox",
 oliver = 50
}

local b: filter<typeof(a), sorter> = {
 oliver = 50
}

Error

you cannot pass a type function sadly, would be cool if we could, i found this approach though it kinda ignore it when declaring table?

--!strict

type function filter(a: type, b: type)
  assert(a:is("table"))
  assert(b:is("singleton"))

  local t = types.newtable()

  for i, v in a:properties() do
    assert(i:is("singleton"))

    if i:value() == b:value() then t:setproperty(i, v.read or v.write) end
  end

  return t
end

local a = {
  jason = 12.5,
  jack = "roblox",
  oliver = 50,
}

local b: filter<typeof(a), "oliver"> = {
  oliver = 50,
  -- j = "", -- wouldnt error??
}

b.| -- Only show oliver

you can do a bunch of elseif chain for different type of sorter which I think is the only solution I can think of?

1 Like