0.3.0 • Published 6 months ago

ts-type-helper v0.3.0

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

ts-type-helper

Add \"missing\" types for Typescript !

Examples:

Strongly typed iterator versions of for (let key of Object.entries(obj))

// key is keyof typeof obj 
// not "string" as with Object.entries(obj) 
for (let key of iterate.entries(obj))

isKeyOf, keyOf and other base functionality to make TS better like an iterator.entries() to replace Object.entires ect.

Why?

For some elements of Typescript type-gymnastics is required to get the correct type.
This library tries to make it easier to get the correct type without having to spend time on type-gymnastics, and still keep the type-safety correct.

Install

npm install --save-dev ts-type-helper

Usage

import the functions or types you need from the library with

import { XXX } from 'ts-type-helper';

Examples

Iterate over object keys and values:

import { interator } from 'ts-type-helper';

const obj = { a: 1, b: 2 };

for (const [key, value] of interator.entries(obj)) {
  // key is 'a' | 'b'
  console.log(key, value);
  // with Object.entries(obj) key would be string
}

Object key check and casting:

import { isKeyOf, keyOf, keyOfCast  } from 'ts-type-helper';

const obj = { a: 1, b: 2 };

for (const key of Object.keys(obj)) {
  // Problem: key is string
  console.log(key, obj[key]) // error
  //  isKeyOf
  if (isKeyOf(key, obj)) {
    console.log(key, obj[key]) // key is 'a' | 'b'
  }
  //  keyOfCast
  var k = keyOfCast(key, obj) // k is 'a' | 'b' | undefined
  console.log(obj[k]) // error (k could be undefined)
  if (k) {
    console.log(obj[k]) // k is 'a' | 'b'
  }
  //  keyOf
  console.log(key, obj[keyOf(key, obj)]) // key is 'a' | 'b'
}
0.3.0

6 months ago

0.2.1

6 months ago

0.2.0

6 months ago

0.2.2

6 months ago

0.1.4

7 months ago

0.1.3

7 months ago

0.1.2

7 months ago

0.1.1

7 months ago

0.1.0

7 months ago