Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Mike Rourke
Added: Jun 20, 2018 2:47 PM
Views: 8
Regexes for converting Flow type definitions to TypeScript.
  1. // Convert Array<any> to any[]:
  2. function replaceArrayDecl() {
  3.   const exampleString = `const testFunc = (): Array<any> => {`;
  4.   const regexGroup = /(.* )(Array<)(\w+)(>)(.*)/g;
  5.   return exampleString.replace(regexGroup, '$1$3[]$5');
  6. }
  7.  
  8. // Replaces Flow's $Shape<> with TypeScript's Partial<>
  9. function replaceShapeWithPartial() {
  10.   const exampleString = `menuItem: $Shape<MenuItem>;`;
  11.   const regex = /\$Shape</;
  12.   return exampleString.replace(regex, 'Partial<');
  13. }
  14.  
  15. // Replaces Flow's $Keys<> with TypeScript's key of
  16. function replaceKeysWithKeyOf() {
  17.   const exampleString = `export type DrugBrand = $Keys<typeof DRUG_BRANDS> | 'All Products';`;
  18.   const regexGroup = /(.* = )(\$Keys<)(typeof )(\w+)(.*>)/;
  19.   return exampleString.replace(regexGroup, '$1keyof $3$4');
  20. }
  21.  
  22. // Fix nullable type (e.g. ?number to number | null):
  23. function fixNullableTypes() {
  24.   const exampleString = 'someValue: ?boolean,';
  25.   const regexGroup = /(.*: )(\?)(\w+)(.*)/g;
  26.   return exampleString.replace(regexGroup, '$1$3 | null$4');
  27. }
  28.  
  29. // Change Flow's read only (+someVar) to TypeScript's (readonly someVar):
  30. function fixReadOnly() {
  31.   const exampleString = '+exampleValue: boolean,';
  32.   const regexGroup = /(\+)(.*)/g;
  33.   return exampleString.replace(regexGroup, 'readonly $2');
  34. }