1.0.1 • Published 6 years ago

ts-nested-key v1.0.1

Weekly downloads
3
License
MIT
Repository
github
Last release
6 years ago

What?

Type safe referencing of nested object properties and a get/set pair of helper functions.

Why?

So you can catch more errors at compile time instead of crying yourself to sleep at night.

How?

Like this:

npm install --save-dev ts-nested-key or yarn add --dev ts-nested-key

import nk, { NestedKey } from "ts-nested-key";

interface Staff {
    name: string;
    boss?: Staff;
}

const bob: Staff = {
    name: "Bob",
    boss: {
        name: "Alice"
    }
};

// This is now a compiler error.
const badKey: NestedKey<Staff> = ["boss", "maim"];

// This is fine.
const goodKey: NestedKey<Staff> = ["boss", "name"];

// To get/set values you don't need a named interface.
const config = {
    one: {
        two: {
            three: 4
        }
    }
};

// You must either declare the var type or specify it as a type argument to
// get/set. Otherwise 'any' is returned. This is a Typescript limitation that
// will hopefully be resolved in a later version.
const value = nk.get<number>(config, ["one", "two", "three"]);
console.log(value); // output: 4

// <number> is here as an example, you only need it if you want the compiler
// to check the third parameter. Again this would be automatic but it's a TS
// limitation for now.
nk.set<number>(config, ["one", "two", "three"], 5);
console.log(config.one.two.three); // output: 5

// set returns true or false depending on whether the value could be set.
console.log(nk.set(bob, ["boss", "name"], "Charles")); // output: true
delete bob.boss;
console.log(nk.set(bob, ["boss", "name"], "Samantha")); // output: false

Not in scope

This library won't create intermediate properties if they don't exist.