einmal
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.2 • Public • Published

    einmal

    A simple function for declaring variables that can be assigned later and only once. This serves few practical purposes, and was mostly a way of getting familiar with the Proxy API.

    Installation

    npm install einmal

    Usage

    Creating an einmal works similar to declaring a variable using const, except that it allows for a single reassignment after being declared. It is important to note that einmal does not make the assigned values immutable. It simply prevents replacing the reference to said value - just like how const works.

    Basic example

    import { einmal } from "einmal";
     
    const thing = einmal();
     
    // first mutation
    thing.value = "this is fine"; // all good
     
    // second mutation
    thing.value = "this will throw"; // throws

    Pitfall - Example with mutable value

    const thing = einmal();
     
    thing.value = { name: "Bob", age: 31 }; // so far so good
     
    // also fine, because we're modifying
    // a property of our target - we're not
    // changing the reference held by our thing
    thing.value.name = "Alice";

    With types

    einmal is written in TypeScript and offers opt-in strong typing for the einmal value.

    type Person = {
      name: string;
      age: number;
    };
     
    const thing = einmal<Person>();

    thing is of type Einmal<Person>. Continued:

    console.log(thing.value.age); // error: value might be undefined
     
    thing.value = { name: "John", age: "yes" }; // also error, since age should be a number

    einmal?

    German: once

    Install

    npm i einmal

    DownloadsWeekly Downloads

    3

    Version

    1.0.2

    License

    MIT

    Unpacked Size

    3.87 kB

    Total Files

    3

    Last publish

    Collaborators

    • janove