Skip to content

Commit

Permalink
feat(is): 添加isTruth(是否为真值)方法
Browse files Browse the repository at this point in the history
  • Loading branch information
renzp94 committed Apr 23, 2024
1 parent 725f7db commit 2efe697
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/_base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,10 @@ export const _toString = (v: unknown): string =>
* 排除undefined和null类型
*/
export type _ExcludeUndefinedNull<T> = T extends undefined | null ? never : T

/**
* 排除假值类型
*/
export type _ExcludeFalsy<T> = T extends false | null | undefined | 0 | ''
? never
: T
18 changes: 17 additions & 1 deletion src/is.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { type _ExcludeUndefinedNull, _toString } from './_base'
import {
type _ExcludeFalsy,
type _ExcludeUndefinedNull,
_toString,
} from './_base'

/**
* 是否为Array类型
Expand Down Expand Up @@ -206,6 +210,18 @@ export const isString = (v: unknown): v is string => typeof v === 'string'
*/
export const isSymbol = (v: unknown): v is symbol => typeof v === 'symbol'

/**
*
* 是否为真值
* @param v 要判断的变量
* @returns 如果是真值则返回true,否则返回false
*
* @example
* isTruth(false); // false
* isTruth(1); // true
*/
export const isTruth = <T = any>(v: T): v is _ExcludeFalsy<T> => !isFalsy(v)

/**
* 是否为undefined
* @param v 要判断的变量
Expand Down
11 changes: 11 additions & 0 deletions test/is.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
isSet,
isString,
isSymbol,
isTruth,
isUnDef,
isUndefined,
} from '../src'
Expand Down Expand Up @@ -135,6 +136,16 @@ test('isSymbol', () => {
expect(isSymbol(0)).toBe(false)
})

test('isTruth', () => {
expect(isTruth(false)).toBe(false)
expect(isTruth(0)).toBe(false)
expect(isTruth('')).toBe(false)
expect(isTruth(null)).toBe(false)
expect(isTruth(undefined)).toBe(false)
expect(isTruth(Number.NaN)).toBe(false)
expect(isTruth(1)).toBe(true)
})

test('isUndefined', () => {
let a: unknown
expect(isUndefined(a)).toBe(true)
Expand Down

0 comments on commit 2efe697

Please sign in to comment.