@harnyk/chan - Go channels for TypeScript
This package is my humble attempt to provide a Chan<T> class for TypeScript, which would be as much as possible similar to Go's chan T type.
Installation
npm install @harnyk/chan
Usage
See the tests and examples for more information.
Brief reference:
| Go equivalent | TypeScript |
|
Create a channel of `number` with no buffer:
|
ch := make(chan int)
|
const ch = new Chan<number>();
|
|
Create a channel of `number` with fixed-size buffer:
|
ch := make(chan int, 5)
|
const ch = new Chan<number>(5);
|
|
Iterate over `Chan` with `for await`
|
for v := range ch {
fmt.Println(v)
}
|
for await (const v of ch) {
console.log(v);
}
|
|
Send a value to `Chan` with `send`
|
ch <- 42
|
await ch.send(42);
|
|
Receive a value from `Chan` with `recv`
|
v, ok := <-ch
|
const [v, ok] = await ch.recv();
|
|
Close `Chan`
|
close(ch)
|
ch.close();
|
|
Select over multiple channels
|
select {
case ch <- 42:
fmt.Println("sent")
case v := <-ch1:
fmt.Printf("Received %d\n", v)
default:
fmt.Println("default")
}
|
await select()
.send(ch, 42, () => console.log('sent'))
.recv(ch1, (v) => console.log(`Received ${v}`))
.default(() => console.log('default'));
|
What is supported
- asynchronous iterating over
Chan<T> with for await
- asynchronous
send and recv
select-ing over multiple channels
License
WTFPL
Contributors
Mark Harnyk (https://github.com/harnyk)
关于 @harnyk/chan 的常见问题
@harnyk/chan 是什么?
This package is my humble attempt to provide a Chan<T> class for TypeScript, which would be as much as possible similar to Go's chan T type.
如何安装 @harnyk/chan?
在项目目录运行 npm install @harnyk/chan,或使用 pnpm add / yarn add / bun add。
@harnyk/chan 支持 TypeScript 吗?
支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。
@harnyk/chan 支持 ESM 还是 CommonJS?
同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。
@harnyk/chan 可以商用吗?
@harnyk/chan 使用 WTFPL 许可。声明的许可为 WTFPL,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。
@harnyk/chan 的下载量有多少?
根据 npm 官方下载统计,@harnyk/chan 在 2026/10/18 – 2026/11/16 这 30 天内被下载 5,465 次,日均约 182 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。
@harnyk/chan 还在维护吗?
最新版本 0.1.1 发布于 2024/07/17(2 年前);至今共发布 9 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/07/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。