Migration + interoperation from TS / JS

Hello, first time around here. I have been looking at tutorials on Youtube, the web, and the documentation here to understand how to migrate from TS / JS. My intent however is on coexistence with an pre-existing TS/JS codebase. I have some basic questions:

  • How do I migrate a component, such that I use the migrated component in as transparent a way as possible from TS/JS components while providing maximal type information and idiomatict rescript. Tall order possibly

I have done several, experiments, here’s one:

Translate this TS:

const Colors = {
    // Number appended reflects the saturation of the color
    primary500: '#72036c',
    primary600: '#640233',
    primary700: "#4e0329",
    primary800: '#3b021f',
    accent500: '#ddb52f',
};

export default Colors;

This is how I translated things to rescript, such that the generated .bs.js is fully usable from TS/JS clients:

type tColors = {
    primary500: string,
    primary600: string,
    primary700: string,
    primary800: string,
    accent500: string,
};

let colors = {
    primary500: "#72036c",
    primary600: "#640233",
    primary700: "#4e0329",
    primary800: "#3b021f",
    accent500: "#ddb52f",
};

%%raw(`
const Colors = colors;
export default Colors;
`)

That generates, this:

// Generated by ReScript, PLEASE EDIT WITH CARE


const Colors = colors;
export default Colors;
;

var colors = {
  primary500: "#72036c",
  primary600: "#640233",
  primary700: "#4e0329",
  primary800: "#3b021f",
  accent500: "#ddb52f"
};

export {
  colors ,
}
/*  Not a pure module */

Now, I see that this migrated code, serves my needs from TS/JS clients, but I am not sure whether it is a “forced non-idiomatic” migration as far as rescript is concerned? If the answer to the latter is yes, then how would I go about doing something that fulfills my two needs?

1 Like

You’ll want to use GenType if you are converting from a TypeScript project.

Example of a React component:

// Component.res
@react.component @gentType
let make = () => <p>{"Hello world!"->React.string}</p>
// App.ts
import { make as Component } from './Component.gen'

export function App() {
  return <Component />
}

For the colors example I would use an object instead of a record to remove the need for the type declaration at the top. Every key is a string so I’m not sure it’s needed.

@genType
let colors = {
  "primary500": "#72036c",
  "primary600": "#640233",
  "primary700": "#4e0329",
  "primary800": "#3b021f",
  "accent500": "#ddb52f",
}

@genType
let default = colors

Outputs:

// Generated by ReScript, PLEASE EDIT WITH CARE

var colors = {
  primary500: "#72036c",
  primary600: "#640233",
  primary700: "#4e0329",
  primary800: "#3b021f",
  accent500: "#ddb52f"
};

var $$default = colors;

export {
  colors ,
  $$default as default,
}
/* No side effect */
1 Like