Skip to content

Something like valueOr but for null? #128

@mnn

Description

@mnn

valueOr works well for | undefined fields, but not for | null fields. I didn't see any function to support this, but maybe I overlooked something?

import * as O from 'optics-ts';

interface ZUndef {
  a?: AUndef;
}

interface AUndef {
  b?: BUndef;
}

interface BUndef {
  x: number;
}

const testUndef = () => {
  const defaultA: AUndef = {};
  const defaultB: BUndef = {x: 7};

  const xO = O.optic<ZUndef>().prop('a').valueOr(defaultA).prop('b').valueOr(defaultB).prop('x');

  const data: ZUndef = {};

  const res = O.set(xO)(11)(data);

  console.log('undef', res); // ok: undef { a: { b: { x: 11 } } }
};

testUndef();

// ---

interface ZNull {
  a: ANull | null;
}

interface ANull {
  b: BNull | null;
}

interface BNull {
  x: number;
}

const testNull = () => {

  const defaultA: ANull = {b: null};
  const defaultB: BNull = {x: 7};

  const xO = O.optic<ZNull>().prop('a').valueOr(defaultA).prop('b').valueOr(defaultB).prop('x'); // TS2345: Argument of type 'string' is not assignable to parameter of type 'never'.

  const data: ZNull = {a: null};

  const res = O.set(xO)(11)(data); // TypeError: Cannot read property 'b' of null

  console.log('null', res);
};

testNull();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions