Coder Social home page Coder Social logo

g-makarov / dot-path-value Goto Github PK

View Code? Open in Web Editor NEW
336.0 5.0 6.0 107 KB

Safely get and set deep nested properties using dot notation.

License: MIT License

TypeScript 97.06% JavaScript 2.94%
dot path typescript get deep value access array notation object

dot-path-value's People

Contributors

ablakey avatar acurrieclark avatar g-makarov avatar saibotk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

dot-path-value's Issues

Wrong type for optional paths

What – Wrong type for optional paths
Expected – string | undefined
Actual – string

Example

import {getByPath} from 'dot-path-value';

import { Equal, Expect } from "@type-challenges/utils";

type AuthorDetails = {
  author?: {
    location?: {
      city: string;
    };
  };
};

const obj: AuthorDetails = {
  author: {
    location: {
      city: "London"
    }
  },
};

const authorLocationCity = getByPath(obj, "author.location.city");

type cases = [
  // ✅ optional path
  Expect<Equal<typeof authorLocationCity, string | undefined>>,
];

TS Playground – https://tsplay.dev/WJ7e6w

Type of property circularly references itself in mapped type

The issue

Given the following code:

import { getByPath } from 'dot-path-value';

type Recursive = {
  a: string;
  r: Recursive;
};

function x(type: Recursive) {
  getByPath(type, '');
  ~~~~~~~~~~~~
}

we get the following error:

Type of property 'r' circularly references itself in mapped type
'{ [K in //keyof Recursive]-?: PathConcat<K & string, Recursive[K]>; }'.(2615)

which makes sense why it would not print until infinity (or at the max TS iterations).

See reproduction

Suggestion

Don't try to infer the fields of the recursive type, or allow inference for only one level deep.

BTW, really cool library, thanks for sharing 🙂

Can `Path<T>` extend string?

I am using getByPath in a helper function and passing in a Path<T> as a parameter. The path is useful to me in another package, which takes an array rather than a "dotted" path. However, attempting path.split('.') throws up a Property 'split' does not exist on type 'Path<T>' typescript error.

function takesPathAsArray(path: string[]) {
  // does something fancy with the path
}

function helperFn<T>(obj: T, path: Path<T>) {
  const value = getByPath(obj, path);

  // error is here                       v v v v v v v v 
  const somethingElse = takesPathAsArray(path.split('.'));
}

I can of course cast path as a string there, but I was wondering if there was a way for the library to support it?

hasByPath()

Hi,

Thanks for the library. It would be great if it provided an hasByPath() method to check the path's availability.

Thanks,

`Path<T>` with numbered object keys

It seems that Path doesn't pick out object keys which are numbers, rather than strings. For example:

const obj = {
  days: {
    1: true,
    "2": false,
    3: true
  }
}

type PathObj = Path<typeof obj>;
//    ^? type PathObj = 'days' | 'days.2'

Example playground for reference

Support 'a.b[0].c' case ?

const obj = {
  a: {
    b: [
      {
        c: 1,
      },
    ],
  },
}
getPath(obj, a.b[0].c) // 1

js is easy, safe type is too difficult 😅.

export function getByPath(
  obj,
  path,
) {
  return path
    .replace(/\[([^\[\]]*)\]/g, '.$1.')
    .split('.')
    .filter(t => t !== '')
    .reduce((prev, cur) => prev && prev[cur], obj)
}

Set by path

Firstly, tremendous typescript expertise on offer here. Lots to learn from.

I was wondering how you might feel about a PR for a setByPath function? I have knocked up a basic one locally using your existing getByPath function.

Let me know and I will put one together!

Wrong type when accessing an array with multiple items

The type of the item accessed is a union of all the types of the items in the array:

const obj = {
    a: {
        b: [
            {
                c: 1,
            },
            'test',
            true
        ],
    },
};

const value = getByPath(obj, 'a.b.1');

In this case the type of value is string | boolean | { c: number; } where it should be string

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.