Coder Social home page Coder Social logo

ts-roids's Introduction

ts-roids

100+ types and decorators to bullet proof TypeScript even more.

tests @latest npm downloads


Installation

npm

npm i ts-roids

pnpm

pnpm i ts-roids

If you're only using types, you can install it as a devDependency. And if you're using decorators, set this.

{
  "compilerOptions": {
    // ...
    "experimentalDecorators": true
  }
}

Requires TypesScript v5.0+

Documentation

Checkout the full API reference for all usage examples with details.

Types

Decorators

Basic Usage

Finalize and freeze objects

import type { Optional, NewType, MaybeUndefined } from 'ts-roids';
import { Final, Frozen } from 'ts-roids';

type Bar = NewType<'Bar', string>;
type Baz = NewType<'Baz', string>;
type Secret = NewType<'Secret', string>;

abstract class BaseFoo<T> {
  abstract requestFoo(secret: Secret, baz: Baz): Optional<T>;
}

@Final
@Frozen
class Foo<T> extends BaseFoo<T> {
  readonly foo: T;
  bar: Optional<Bar>;

  constructor(foo: T, bar?: MaybeUndefined<Bar>) {
    super();
    this.foo = foo;
    this.bar = bar ?? null;
  }


  requestFoo(secret: Secret, baz: Baz): Optional<T> {
    // A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value
    if (
      secret.concat().toLowerCase() === '123' &&
      baz.concat().toLowerCase() === 'baz' &&
      this.bar !== null
    ) {
      return this.foo;
    }

    return null; // So you have to explicitly return null here.
  }
}

class SubFoo extends Foo<string> {
  constructor(foo: string) {
    super(foo);
  }
}

// No problem with instantiation
const foo = new Foo<string>('foo');

// Since the object is final:

// The line below will cause a TypeError: Cannot inherit from the final class Foo
const _ = new SubFoo('subFoo');

// Since the object is frozen:

// The line below will cause a TypeError: Cannot add property 'requestFoo', object is not extensible
foo.requestFoo = () => {
  return 'not foo';
};

// The line below will cause a TypeError: Cannot assign to read only property 'bar'
foo.bar = 'not bar' as Bar;

The TypeScript team has not yet introduced a built-in final modifier yet, check this, this and many other requests. Although they introduced override in v4.3 .

Decorators like @Final provide a limited way to emulate final behavior, these are merely band-aids for now, until TS officially supports a true final modifier.

You can also seal an object btw.

@Sealed
class Person {
  constructor(name: string, age?: number) {}
}

const john = new Person('John', 30);

// Existing properties can still be modified
john.age = 31; // No Errors

// Existing properties cannot be re-configured nor deleted

(john as any).email = '[email protected]'; // TypeError: Cannot add property email,
// object is not extensible

delete john.age; // TypeError: Cannot delete property 'age' 

Changelog

See releases.

License

GPL-3

ts-roids's People

Contributors

ashgw avatar dependabot[bot] avatar

Stargazers

Pert Urbo avatar Maxime avatar nwhitmont avatar Sevdalin Sabev avatar AndreiTS avatar Hassan Khan avatar Luis Ventura avatar  avatar  avatar Ashref Gwader avatar neXos avatar

Watchers

 avatar

ts-roids's Issues

Add `IsUnknown` type

New feature motivation

_

New feature description

_

New feature implementation

No response

Create a `ArrayFilter<Arr,P>`

New feature motivation

_

New feature description

This filters an array T based on a predicate P and returns an array of elements of T that match P

New feature implementation

No response

Add Python's `NewType`

New feature motivation

In TS it's known as branding, but I did Callable<ArgType,Rtype> resembling python's, I'm doing this too

New feature description

_

New feature implementation

_

Add `IsNever` type

New feature motivation

_

New feature description

_

New feature implementation

No response

Add `UniqueArray<T>`

New feature motivation

Accepts an array T, and gives an array of unique elements

New feature description

_

New feature implementation

No response

Make `OneOrMany` type

New feature motivation

_

New feature description

_

New feature implementation

No response

Add `Transpose<Arr>`

New feature motivation

_

New feature description

_

New feature implementation

_

Add `mutableKeys<T>`

New feature motivation

Picks all the mutable keys of T into a union.

New feature description

_

New feature implementation

No response

setup workflows

New feature motivation

_

New feature description

_

New feature implementation

No response

Add `IsTruthy` type

New feature motivation

_

New feature description

_

New feature implementation

No response

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.