接口
Targo 接口遵循 Go 风格契约。当接口用于建模真正的 Go interface 时,需要使用 GoInterface 标记。
核心规则
- 使用接口定义行为边界和可替换性
- 带 Go 风格方法的接口应 extend
GoInterface - 优先使用 Go 风格方法签名(包括
[T, error | null]元组返回),而不是 JavaScript 风格回调契约 - 不要假设 TypeScript
implements习惯就是正确的。以当前 Targo checker 行为和声明为准
定义 Go Interface
typescript
interface Reader extends GoInterface {
Read(p: slice<byte>): [int, error | null];
}当类型需要表现为 Go interface 边界时使用 GoInterface,特别是导入的 Go API 或需要编译为 interface 契约的 Targo 声明。
Class 与 Interface 兼容性
Class 可以参与面向接口的设计,但方法形状必须匹配 Targo 和 Go 的预期。
typescript
interface Runner extends GoInterface {
Run(name: string): error | null;
}
class TaskRunner {
Run(name: string): error | null {
if (name == "") {
return new Error("name is required");
}
return null;
}
}保持方法声明显式且 Go 风格。当目标是满足 Go interface 契约时,避免使用属性方法模式。
何时使用其他工具
- 使用
Embedding<{ ... }>()进行 Go 风格结构体嵌入 - 使用
DefinedType<...>()创建 Go defined type,而不仅仅是 interface 边界 - 当建模本地对象行为而非 Go interface 契约时,使用不带
GoInterface的普通 class
常见错误
- 忘记在需要建模 Go interface 的接口上加
GoInterface - 假设普通 TypeScript interface 模式会自动编译为相同的 Go 契约
- 把带方法的属性和 Go 方法混为一谈
- 用继承代替接口加组合