Hey,
from time to time I need a function, which accepts any records.
Here is an example:
let getKeysOfRecord = record => {
record->Obj.magic->Dict.keysToArray
}
type test1 = {
foo: string,
bar: string,
baz: int,
}
type test2 = {
x: int,
y: int,
}
These function calls will work:
testToDict->getKeysOfRecord({foo: "hello", bar: "world", baz: 1})->Console.log
testToDict->getKeysOfRecord({x: 1, y: 2})->Console.log
Unfortunately I could also pass anything else:
getKeysOfRecord("hello world")->Console.log
I know, I could also use objects, but I don’t like them:
let getKeysOfRecord = (record: {..}) => {
record->Obj.magic->Dict.keysToArray
}
getKeysOfRecord({"foo": "hello", "bar": "world", "baz": 1})->Console.log
Or I get rid of the Obj.magic
, by creating converters for my records:
let getKeysOfRecord = record => {
record->Dict.keysToArray
}
external test1ToDict: test1 => Dict.t<'a> = "%identity"
external test2ToDict: test2 => Dict.t<'a> = "%identity"
test1ToDict({foo: "hello", bar: "world", baz: 1})->getKeysOfRecord->Console.log
TLDR;
Would it be feasible and possible to have a syntax for all record types?
let getKeysOfRecord = (record: {|..|}) => {
record->Record.toDict->Dict.keysToArray
}
Cheers
Daniel