Convert types of similar shape

Is there an idiomatic way to convert between types of similar shapes?

Is there a better way to convert aValue to type b here?

type a = {one: string, two: int, three: bool}
type b = {one: string, two: int, three: bool}

let aValue: a = {one: "one", two: 1, three: true}
let bValue: b = {one: aValue.one, two: aValue.two, three: aValue.three}

if they are identical:
external aToB: a => b = “%identity”

either way make a function for it and dont worry =)
(or unify types?)

1 Like

I would use object types and row polymorphism

2 Likes

Great idea, hadn’t thought about using identity myself. Think I’ll go for this.
Unifying the types would be ideal, but not an option for the use case I have ( generated types that sometimes overlap / have similar structures )

Thanks, how would that look in this example?

type a = {"one": string, "two": int, "three": bool}
type b = {"one": string, "two": int, "three": bool}

let aValue: a = {"one": "one", "two": 1, "three": true}
let bValue: b = {"one": "one", "two": 1, "three": true}

let bCanBeA: b = aValue

let someFn = (value: a) => {
  Js.log(value)
}

someFn(aValue)
someFn(bValue)

Structural objects are type-checked on their structural attributes, that allows you to mix and match values of types that have a similar structure.

1 Like

Thanks, that is good to know :+1: