golang类型检查与TypeScript声明导出插件库typex的使用
Golang类型检查与TypeScript声明导出插件库typex的使用
typex是一个用于检查Go类型及其传递性依赖关系的工具,可以将结果导出为TypeScript值对象或类型的声明。
安装
go install github.com/dtgorski/typex@latest
简介
CLI命令typex
可以过滤和显示Go类型结构、接口及其跨包边界的关联关系。它会生成一个类型层次结构树,并包含对过滤类型至关重要的传递性依赖的额外引用。作为附加功能,typex
可以将结果树导出为TypeScript的投影,表示值对象或纯类型。
示例
Go类型层次结构布局
$ typex -f=Rune io/...
├── error interface {
│ Error() string
│ }
└── io
├── RuneReader interface {
│ ReadRune() (r rune, size int, err error)
│ }
└── RuneScanner interface {
io.RuneReader
ReadRune() (r rune, size int, err error)
UnreadRune() error
}
$ typex -f=Render github.com/dtgorski/typex/...
└── github.com
└── dtgorski
└── typex
└── internal
├── PathReplaceFunc func(string) string
├── go
│ └── TypeRender struct {
│ PathReplaceFunc internal.PathReplaceFunc
│ IncludeUnexported bool
│ }
└── ts
└── TypeRender struct {
PathReplaceFunc internal.PathReplaceFunc
IncludeUnexported bool
}
TypeScript值对象布局
$ typex -f=File -l=ts-class mime/multipart
export module mime {
export module multipart {
export class FileHeader {
constructor(
readonly Filename: string,
readonly Header: net.textproto.MIMEHeader,
readonly Size: number,
) {}
}
}
}
export module net {
export module textproto {
export type MIMEHeader = Record<string, string[]>
}
}
TypeScript纯类型布局
$ typex -f=File -l=ts-type mime/multipart
export module mime {
export module multipart {
export type FileHeader = {
Filename: string,
Header: net.textproto.MIMEHeader,
Size: number,
}
}
}
export module net {
export module textproto {
export type MIMEHeader = Record<string, string[]>
}
}
TypeScript与保留关键字
基本上,类型和字段的名称将从Go导出而不做修改。可能会与目标语言中的保留关键字或标准类型名称发生冲突。为避免冲突,您可以使用结构导出字段的JSON标签注释。
TypeScript与可导出类型
由于基本语言差异,typex
无法将所有类型声明一对一导出。请参考下面的类型映射表。Go的通道、接口和函数声明将被省略,对这些类型的引用将使用any
类型。
TypeScript类型映射
TypeScript(即JavaScript或ECMAScript)缺乏原生整数类型。那里提供的数字类型本质上是一个64位浮点数。在处理导出的数字类型时应该记住这一点,这包括byte
和rune
类型别名。
Go原生类型 | TypeScript类型 |
---|---|
bool |
boolean |
string |
string |
map |
Record<K, V> |
struct (named) |
T |
struct (anonymous) |
{} |
array (slice) |
T[] |
complex [64 |
128 ] |
chan , func , interface |
any |
int [8 |
16 |
uint [8 |
16 |
byte (=uint8) |
number |
rune (=int32) |
number |
float [32 |
64 ] |
uintptr |
number |
使用
$ typex -h
Usage: typex [options] package...
Examine Go types and their transitive dependencies. Export
results as TypeScript value objects (or types) declaration.
Options:
-f <name>
Type name filter expression. Repeating the -f option
is allowed, all expressions aggregate to an OR query.
The <name> filter can be a type name, a path part or
a regular expression. Especially in the latter case,
<name> should be quoted or escaped correctly to avoid
errors during shell interpolation. Filters are case
sensitive, see examples below.
The result tree will contain additional references to
transitive dependencies vital for the filtered types.
-l <layout>
Modify the export layout. Available layouts are:
* "go": the default Go type dependency tree
* "ts-type": TypeScript type declaration projection
* "ts-class": TypeScript value object projection
-r <old-path>:<new-path>
Replace matching portions of <old-path> in a fully
qualified type name with <new-path> string. Repeating
the -r option is allowed, substitutions will perform
successively. <old-path> can be a regular expression.
The path replacement/relocation can be used to modify
locations of type hierarchies, e.g. prune off the
"github.com" reference from qualified type name path
by omitting the <new-path> part after the colon.
-t Go tests (files suffixed _test.go) will be included
in the result tree available for a filter expression
-u Unexported types (lowercase names) will be included
in the result tree available for a filter expression.
-x <name>
Exclude type names from export. Repeating this option
is allowed, all expressions aggregate to an OR query.
The exclusion filter can be a type name, a path part
or a regular expression.
More options:
-h Display this usage help and exit.
-v Print program version and exit.
The 'package' argument denotes one or more package import path
patterns to be inspected. Patterns must be separated by space.
A pattern containing '...' specifies the active modules whose
modules paths match the pattern.
Examples:
$ typex -u go/...
$ typex -u -f=URL net/url
$ typex github.com/your/repository/...
$ typex -l=ts-type github.com/your/repository/...
$ typex -r=github.com:a/b/c github.com/your/repository/...
This tool relies heavily on Go's package managing subsystem and
is bound to its features and environmental execution context.
已知问题
- 在Go 1.14.6 darwin/amd64上偶尔(?)会从Go的包管理子系统中报告
internal error
。更新的Go版本>=1.15似乎不受影响。
免责声明
typex
的实现和功能遵循YAGNI原则。不保证完整性和可靠性。
@dev
尝试make
:
$ make
make help Displays this list
make clean Removes build/test artifacts
make build Builds a static binary to ./bin/typex
make debug Starts debugger [:2345] with ./bin/typex
make install Compiles and installs typex in Go environment
make test Runs tests, reports coverage
make tidy Formats source files, cleans go.mod
make sniff Checks format and runs linter (void on success)
许可证
MIT - © dtg [at] lengo [dot] org
更多关于golang类型检查与TypeScript声明导出插件库typex的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang类型检查与TypeScript声明导出插件库typex的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang 类型检查与 TypeScript 声明导出插件库 typex 使用指南
Golang 类型检查
Golang 是静态类型语言,编译器会在编译时进行严格的类型检查。以下是 Golang 类型检查的关键点:
- 变量类型声明:变量必须明确声明类型或通过初始值推断类型
- 函数参数类型:函数参数和返回值必须指定类型
- 接口实现检查:结构体必须实现接口的所有方法
示例代码
package main
import "fmt"
// 接口定义
type Animal interface {
Speak() string
}
// Dog 类型实现 Animal 接口
type Dog struct{}
func (d Dog) Speak() string {
return "Woof!"
}
// 类型检查函数
func CheckType(a Animal) {
fmt.Println(a.Speak())
}
func main() {
dog := Dog{}
CheckType(dog) // 类型检查通过
// 以下代码会导致编译错误,因为 int 不实现 Animal 接口
// num := 42
// CheckType(num)
}
TypeScript 声明导出插件库 typex
typex 是一个可以将 Go 类型导出为 TypeScript 声明的工具,特别适合需要前后端类型同步的项目。
安装 typex
go get github.com/dave/typex
基本使用
- 首先在 Go 代码中添加注释标记:
package models
// User represents a user in the system
// typex:export
type User struct {
// typex:export
ID int `json:"id"`
// typex:export
Username string `json:"username"`
// typex:export
Email string `json:"email"`
Password string `json:"-"` // 不会被导出
}
// typex:export
type ApiResponse struct {
// typex:export
Success bool `json:"success"`
// typex:export
Data interface{} `json:"data"`
// typex:export
Error string `json:"error,omitempty"`
}
- 创建导出命令:
typex -input ./models -output ./frontend/types/generated.d.ts
高级配置
可以创建 typex.yaml
配置文件:
input:
- ./models
- ./api
output: ./frontend/types/generated.d.ts
options:
uppercase: true
ignore:
- Password
- internal.*
生成的 TypeScript 声明示例
// generated.d.ts
interface User {
id: number;
username: string;
email: string;
}
interface ApiResponse<T = any> {
success: boolean;
data: T;
error?: string;
}
实际项目集成建议
- 自动化流程:将 typex 集成到构建流程中,确保类型同步
- 版本控制:将生成的 .d.ts 文件纳入版本控制
- 文档注释:Go 的注释会转换为 TypeScript 的文档注释
示例构建脚本
#!/bin/bash
# 生成 TypeScript 类型声明
typex -config typex.yaml
# 格式化生成的代码
prettier --write frontend/types/generated.d.ts
注意事项
- 复杂类型(如嵌套结构体、自定义类型别名)可能需要额外配置
- 某些 Go 类型(如 time.Time)需要特殊处理
- 类型导出是单向的,TypeScript 端的修改不会影响 Go 代码
通过合理使用 typex,可以显著提高全栈开发效率,减少类型不一致导致的错误。