typescript-is icon indicating copy to clipboard operation
typescript-is copied to clipboard

Feature: Support integer or adding custom type

Open Web-Engine opened this issue 3 years ago • 1 comments

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

Web-Engine avatar Feb 16 '21 09:02 Web-Engine

Possible by writing comment:

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

samchon avatar Oct 10 '22 15:10 samchon