woutervh- / typescript-is

MIT License
959 stars 35 forks source link

Feature: Support integer or adding custom type #90

Open Web-Engine opened 3 years ago

Web-Engine commented 3 years ago

I want to check the value is a integer not number.

type integer = number;

interface Test {
  foo: integer;
  bar: string;
}

const isTest(obj: any): obj is Test => {
  if (!Number.isInteger(obj?.foo)) return false;
  if (typeof obj?.bar !== 'string') return false;

  return true;
}

const good = {
  foo: 1,
  bar: 'good',
};

const bad = {
  foo: 1.234,
  bar: 'bad',
};

console.log(isTest(good)); // true
console.log(isTest(bad)); // false

makes like:

import { is, integer } from 'typescript-is';

interface Test {
  foo: integer;
  bar: string;
}

const good = {
  foo: 1,
  bar: 'good',
};

const bad = {
  foo: 1.234,
  bar: 'bad',
};

console.log(is<Test>(good)); // true
console.log(is<Test>(bad)); // false

or

import { is, addType } from 'typescript-is';

type integer = number;
addType<integer>((obj: any): obj is integer => Number.isInteger(obj));

interface Test {
  foo: integer;
  bar: string;
}

const good = {
  foo: 1,
  bar: 'good',
};

const bad = {
  foo: 1.234,
  bar: 'bad',
};

console.log(is<Test>(good)); // true
console.log(is<Test>(bad)); // false
samchon commented 2 years ago

Possible by writing comment:

https://github.com/samchon/typescript-json#comment-tags