fast-csv icon indicating copy to clipboard operation
fast-csv copied to clipboard

[FEATURE] Support transform FormatterOptionsArgs of type 'A -> A | B -> B'

Open varun-dc opened this issue 2 years ago • 0 comments

Parsing or Formatting?

  • [x] Formatting
  • [ ] Parsing

Is your feature request related to a problem? Please describe.

type RowMap = Record<string, unknown>;
type RowArray = unknown[];
type SyncRowTransform =
  | ((row: RowArray) => RowArray)
  | ((row: RowMap) => RowMap);

function myFunction(...): ... {
  return fastCsv.format({
    delimiter,
    includeEndRowDelimiter: true,

    // Please ignore the fact I have 3 duplicate `transform` keys here, this is
    // only for demonstration purposes

    transform: getTransformer(driver) as any,
    // getTransformer is a function that I've omitted here, but it returns a `SyncRowTransform`
    // The typing for `transform` doesn't seem to accept a `(A -> A) | (B -> B)`
    // function and instead want a `(A | B) -> (A | B)` function. So an explicit cast
    // here is necessary

    transform: true ? t1 : t1,
    // This type checks fine

    transform: true ? t2 : t3,
    // But this doesn't type check
    // [tsserver 2322] [E] Type '((row: RowArray) => RowArray) | ((row: RowMap) => RowMap)' is not assignable to type 'RowTransformFunction<RowArray, RowArray> | undefined'.
    //   Type '(row: RowMap) => RowMap' is not assignable to type 'RowTransformFunction<RowArray, RowArray> | undefined'.
    //     Type '(row: RowMap) => RowMap' is not assignable to type 'SyncRowTransform<RowArray, RowArray>'.
    //       Types of parameters 'row' and 'row' are incompatible.
    //         Type 'RowArray' is not assignable to type 'RowMap'.
    //           Index signature for type 'string' is missing in type 'unknown[]'.
  });
}

function t1(row: RowMap | RowArray): RowMap | RowArray {
  return row;
}

function t2(row: RowArray): RowArray {
  return row;
}

function t3(row: RowMap): RowMap {
  return row;
}

Describe the solution you'd like Support transform functions of the type

type SyncRowTransform =
  | ((row: RowArray) => RowArray)
  | ((row: RowMap) => RowMap);

If it's not going cause problems for everyone else using this package.

Describe alternatives you've considered

We can just do a hard cast to bypass the issue. It seems to work fine when I try it out locally in my project.

Additional comments Could we potentially support

(A | B -> A | B) | (A -> A) | (B -> B)

Where A is RowArray and B is RowMap, so that we retain backward compatibility?

varun-dc avatar Apr 11 '22 19:04 varun-dc