@detachhead/ts-helpers

中文文档
16.2.0发布于 2023/09/19ISCTypeScriptCommonJS近 30 天下载 3242

various typescript helper functions and utility types

原始使用文档
文档目录10 节
  1. features
  2. value tracking
  3. noUncheckedIndexedAccess support
  4. date formatter type
  5. Type Testing
  6. variance modifier types
  7. casting functions
  8. requirements
  9. typescript
  10. runtime

ts-helpers

various typescript helper functions and utility types

npm

features

value tracking

this library includes many helper types and functions such as add, subtract, and substring which allow the values to be known at compile time

asdf

noUncheckedIndexedAccess support

the noUncheckedIndexedAccess compiler flag is epic, but there's room for improvement. for example, the following issue:

if (foo.length > 2) {
    const bar: string = foo[1] //error: string | undefined not assignable to string
}

can be solved with lengthGreaterThan

import { lengthGreaterThan } from '@detachhead/ts-helpers/dist/functions/Number'

if (lengthGreaterThan(foo, 2)) {
    const bar: string = foo[1] //no error, foo is casted to [string, string]
}

there's also lengthLessThan, lengthGreaterOrEqual, etc.

most of the array functions in this library keep track of the length, mostly thanks to this TupleOf utility type

date formatter type

this library contains a helper type and function for formatting dates using the date-fns format.

import { formatDate } from '@detachhead/ts-helpers/dist/functions/Date'

const date = formatDate(new Date(), 'dd-MM-yyyy')

assert(date === '01/01/2021') //compile error, wrong date format

you can use any date format that date-fns accepts, and the FormatDate utility type will generate a template literal type to match your desired date format.

Type Testing

With the exactly function you can test if types or values are an exact match to a type

import { exactly } from '@detachhead/ts-helpers/dist/functions/misc'

const a: 1 | 2 = 1
//values (also does a runtime assertion on the values)
exactly(1 as number, a) // error as `1 | 2` is not an exact match of `number`
exactly(1 as number, a as number) // no error
exactly(1 as 1 | 2, a) // no error

// mixed
exactly<number>()(a) // error as `1 | 2` is not an exact match of `number`
exactly<number>()(a as number) // no error
exactly<1 | 2>()(a) // no error

// types
type Foo = 1 | 2
exactly<1, Foo>() // error as `1 | 2` is not an exact match of `1`
exactly<1 | 2, Foo>() // no error

The Equals type allows you to check if two types are equal at the type level

import { Equals } from '@detachhead/ts-helpers/dist/types/misc'

type Foo = Equals<number, 1 | 2> // false
type Bar = Equals<any, 10> // false
type Baz = Equals<unknown, never> // false

variance modifier types

when using the old method syntax, typescript does not check the variance on assignment:

declare class A<T> {
    set(value: T): void
    get(): T
}

const a = new A<number>()

const b: A<unknown> = a

b.set('')
a.get() // typescript thinks this is a number but it's actually a string

for more information about how variance works, see this PR. the TL;DR is basically that arrow functions are checked more strictly than the old method syntax (for backwards compatibility reasons). this means you should be using arrow functions where possible.

declare class A<T> {
    set: (value: T) => void
    get: () => T
}

const a = new A<number>()

const b: A<unknown> = a // error: Type 'A<number>' is not assignable to type 'A<unknown>'

unfortunately however, arrow functions can't always be used. sometimes you need to use methods instead if, for example, you need to access super from a subclass:

class B extends A<number> {
    get = () => super.get() // runtime error, arrow functions can't access super
}

this is where variance modifiers come in

SafeVariance / ToArrowFunction

you can use SafeVariance<A> to enable strict variance checking on a class that has methods in it. or if for whatever reason you need to convert an individual function type to an arrow function type, you can use ToArrowFunction<A['get']>

import { SafeVariance, ToArrowFunction } from '@detachhead/ts-helpers/dist/types/Function'

class B<T> extends A<T> {
    override get() {
        return super.get()
    }
}

const a = new B<number>()

const b: SafeVariance<A<unknown>> = a // error

UnsafeVariance / ToNonArrowFunction

variance is only an issue when you're dealing with classes that have mutable state. if your type is immutable, you may want to disable variance checking without having to convert your shiny new arrow functions into cringe old methods.

to do this, simply use UnsafeVariance<A> on your class, or ToNonArrowFunction<A['set']> to convert a function type:

import { ToNonArrowFunction, UnsafeVariance } from '@detachhead/ts-helpers/dist/types/Function'

declare class A<T> {
    doSomethingElseThatTotallyDoesntChangeTheValue: (value: T) => void
    get: () => T
}

const a = new A<number>()

const b: UnsafeVariance<A<unknown>> = a // no error

drawbacks

it goes without saying that these modifiers do not change the runtime behavior of a function. an arrow function is still an arrow function regardless of whether you use the ToNonArrowFunction type on it.

casting functions

import { narrow, narrowCast, unsafeNarrow } from '@detachhead/ts-helpers/dist/functions/misc'

the as keyword doesn't always work exactly how you want. the narrow, unsafeNarrow and narrowCast functions can be used to cast variables in different ways

modifies original variable's typereturns the value with the casted typeintersects original type with casted typeallows non-overlapping types
as keywordyes
narrow functionyesyes
unsafeNarrow functionyesyesyes
narrowCast functionyesyesyes

requirements

typescript

since this package pushes the limits of the typescript compiler, i often update it to depend on unreleased versions of typescript for bug fixes and to ensure that upcoming releases won't break any of my wacky types. currently it depends on typescript >=5.0. you will probably encounter type errors and/or performance issues trying to use it with older versions.

runtime

as long as it supports es2021 you should be good. tested on:

  • nodejs >=15
  • browsers (chrome >=85)
  • deno (using esm.sh - eg. import { exactly } from 'http://esm.sh/@detachhead/ts-helpers/dist/utilityFunctions/misc')

版本与发布记录

@detachhead/ts-helpers 共发布 233 个版本,首次发布于 2021/01/12;过去 12 个月发布了 0 个版本。

版本发布日期距今
16.2.0latest2023/09/193 年前
16.1.0-8075f1b69fcb8e43f9190d228d110fd30d45f9fccanary2023/09/193 年前
16.1.0-4d936d7f443b76961f9cc384ab5fa4cabe73bf9d2023/07/243 年前
16.1.0-2467287e1c6ba90ad367c35fbdea72696b04d8272023/07/243 年前
16.1.0-f64e5159dba50b1b14d5e79bcbd36ef96ff3ce672023/07/243 年前
16.1.0-064bd6e36fa1652dd72ff70f5ea2228eb7d089242023/07/243 年前

关于 @detachhead/ts-helpers 的常见问题

@detachhead/ts-helpers 是什么?

various typescript helper functions and utility types

如何安装 @detachhead/ts-helpers?

在项目目录运行 npm install @detachhead/ts-helpers,或使用 pnpm add / yarn add / bun add。

@detachhead/ts-helpers 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@detachhead/ts-helpers 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@detachhead/ts-helpers 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.6.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@detachhead/ts-helpers 可以商用吗?

@detachhead/ts-helpers 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@detachhead/ts-helpers 的下载量有多少?

根据 npm 官方下载统计,@detachhead/ts-helpers 在 2026/10/12 – 2026/11/10 这 30 天内被下载 3,242 次,日均约 108 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@detachhead/ts-helpers 还在维护吗?

最新版本 16.2.0 发布于 2023/09/19(3 年前);至今共发布 233 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/01/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。