typespec 是一个强大的api 描述框架,以下是一个简单的试用

安装typespec

可以安装为全局cli

  • 命令
npm install -g @typespec/compiler

使用

  • 创建项目
tsp init // 后续按照提示操作,可以选择http
  • 安装依赖
tsp install
  • 项目结构
├── main.tsp
├── package-lock.json
├── package.json
└── tspconfig.yaml
  • 代码简单说明

tspconfig.yaml

emit:
- "@typespec/openapi3"

package.json

{
  "name": "demo",
  "version": "0.1.0",
  "type": "module",
  "dependencies": {
    "@typespec/compiler": "latest",
    "@typespec/http": "latest",
    "@typespec/openapi3": "latest"
  },
  "private": true
}
"name": "demo",

main.tsp

import "@typespec/http";
 
using TypeSpec.Http;
 
model Pet {
  name: string;
  age: int32;
}
 
model Store {
  name: string;
  address: Address;
}
 
model Address {
  street: string;
  city: string;
}
 
@route("/pets")
interface Pets {
  list(@query filter: string): Pet[];
  create(@body pet: Pet): Pet;
  read(@path id: string): Pet;
}
 
@route("/stores")
interface Stores {
  list(@query filter: string): Store[];
  read(@path id: Store): Store;
}
  • 编译
tsp compile .
  • 效果

typespec 简单试用_参考资料

说明

以上是一个简单的试用,typespec 还是很强大的,值得学习试用下,对于开发api first 的架构很值得参考

参考资料

https://typespec.io/
https://github.com/microsoft/typespec