deno-typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDeno TypeScript Development
Deno TypeScript 开发指南
You are an expert in Deno and TypeScript development with deep knowledge of building secure, modern applications using Deno's native TypeScript support and built-in tooling.
您是Deno与TypeScript开发专家,精通利用Deno的原生TypeScript支持和内置工具构建安全、现代化的应用。
TypeScript General Guidelines
TypeScript 通用规范
Basic Principles
基本原则
- Use English for all code and documentation
- Always declare types for variables and functions (parameters and return values)
- Avoid using type - create necessary types instead
any - Use JSDoc to document public classes and methods
- Write concise, maintainable, and technically accurate code
- Use functional and declarative programming patterns
- No configuration needed - Deno runs TypeScript natively
- 所有代码和文档使用英文
- 始终为变量和函数(参数及返回值)声明类型
- 避免使用类型,而是创建必要的自定义类型
any - 使用JSDoc为公共类和方法编写文档
- 编写简洁、可维护且技术准确的代码
- 使用函数式和声明式编程模式
- 无需配置,Deno原生支持TypeScript运行
Nomenclature
命名规范
- Use PascalCase for classes, types, and interfaces
- Use camelCase for variables, functions, and methods
- Use kebab-case for file and directory names
- Use UPPERCASE for environment variables
- Use descriptive variable names with auxiliary verbs: ,
isLoading,hasErrorcanDelete - Start each function with a verb
- 类、类型和接口使用PascalCase命名
- 变量、函数和方法使用camelCase命名
- 文件和目录名称使用kebab-case命名
- 环境变量使用全大写命名
- 使用带有助动词的描述性变量名:、
isLoading、hasErrorcanDelete - 每个函数以动词开头
Functions
函数规范
- Write short functions with a single purpose
- Use arrow functions for simple operations
- Use async/await for asynchronous operations
- Prefer the RO-RO pattern for multiple parameters
- 编写单一职责的短小函数
- 简单操作使用箭头函数
- 异步操作使用async/await
- 多参数优先使用RO-RO模式(请求-响应模式)
Types and Interfaces
类型与接口规范
- Prefer interfaces over types for object shapes
- Avoid enums; use const objects with
as const - Use Zod for runtime validation with inferred types
- Use for immutable properties
readonly
- 定义对象结构时优先使用接口而非类型别名
- 避免使用枚举,使用修饰的常量对象替代
as const - 使用Zod进行运行时验证并推导类型
- 不可变属性使用修饰
readonly
Deno-Specific Guidelines
Deno 专属规范
Project Structure
项目结构
src/
routes/
{resource}/
mod.ts
handlers.ts
validators.ts
middleware/
auth.ts
logger.ts
services/
{domain}_service.ts
types/
mod.ts
utils/
mod.ts
deps.ts
main.ts
deno.jsonsrc/
routes/
{resource}/
mod.ts
handlers.ts
validators.ts
middleware/
auth.ts
logger.ts
services/
{domain}_service.ts
types/
mod.ts
utils/
mod.ts
deps.ts
main.ts
deno.jsonModule System
模块系统
- Use ES modules with explicit file extensions
- Use pattern for centralized dependency management
deps.ts - Import from URLs or use import maps in
deno.json - Use JSR (jsr.io) for Deno-native packages
typescript
// deps.ts - centralized dependencies
export { serve } from "https://deno.land/std@0.208.0/http/server.ts";
export { z } from "https://deno.land/x/zod@v3.22.4/mod.ts";
// Using import maps in deno.json
{
"imports": {
"std/": "https://deno.land/std@0.208.0/",
"hono": "https://deno.land/x/hono@v3.11.7/mod.ts"
}
}- 使用带明确文件扩展名的ES模块
- 使用模式进行集中式依赖管理
deps.ts - 从URL导入,或在中使用导入映射
deno.json - 针对Deno原生包使用JSR(jsr.io)
typescript
// deps.ts - 集中式依赖管理
export { serve } from "https://deno.land/std@0.208.0/http/server.ts";
export { z } from "https://deno.land/x/zod@v3.22.4/mod.ts";
// 在deno.json中使用导入映射
{
"imports": {
"std/": "https://deno.land/std@0.208.0/",
"hono": "https://deno.land/x/hono@v3.11.7/mod.ts"
}
}Security Model
安全模型
Deno is secure by default. Request only necessary permissions:
bash
undefinedDeno默认是安全的,仅请求必要的权限:
bash
undefinedRun with specific permissions
使用特定权限运行
deno run --allow-net --allow-read=./data --allow-env main.ts
deno run --allow-net --allow-read=./data --allow-env main.ts
Permission flags
权限标识
--allow-net=example.com # Network access to specific domains
--allow-read=./path # File read access
--allow-write=./path # File write access
--allow-env=API_KEY # Environment variable access
--allow-run=cmd # Subprocess execution
```typescript
// Programmatic permission requests
const status = await Deno.permissions.request({ name: "net", host: "api.example.com" });
if (status.state === "granted") {
// Network access granted
}--allow-net=example.com # 访问特定域名的网络权限
--allow-read=./path # 文件读取权限
--allow-write=./path # 文件写入权限
--allow-env=API_KEY # 环境变量访问权限
--allow-run=cmd # 子进程执行权限
```typescript
// 程序化请求权限
const status = await Deno.permissions.request({ name: "net", host: "api.example.com" });
if (status.state === "granted") {
// 已授予网络权限
}HTTP Server with Deno.serve
使用Deno.serve搭建HTTP服务器
typescript
// Simple HTTP server
Deno.serve({ port: 8000 }, (req) => {
const url = new URL(req.url);
if (url.pathname === "/api/users" && req.method === "GET") {
return Response.json({ users: [] });
}
return new Response("Not Found", { status: 404 });
});typescript
// 简单HTTP服务器
Deno.serve({ port: 8000 }, (req) => {
const url = new URL(req.url);
if (url.pathname === "/api/users" && req.method === "GET") {
return Response.json({ users: [] });
}
return new Response("Not Found", { status: 404 });
});Using Hono with Deno
在Deno中使用Hono
typescript
import { Hono } from "https://deno.land/x/hono/mod.ts";
const app = new Hono();
app.get("/", (c) => c.text("Hello Deno!"));
app.get("/api/users", (c) => c.json({ users: [] }));
Deno.serve(app.fetch);typescript
import { Hono } from "https://deno.land/x/hono/mod.ts";
const app = new Hono();
app.get("/", (c) => c.text("Hello Deno!"));
app.get("/api/users", (c) => c.json({ users: [] }));
Deno.serve(app.fetch);Using Fresh Framework
使用Fresh框架
typescript
// routes/index.tsx
import { PageProps } from "$fresh/server.ts";
export default function Home(props: PageProps) {
return (
<div>
<h1>Welcome to Fresh</h1>
</div>
);
}
// routes/api/users.ts
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
async GET(_req, _ctx) {
const users = await getUsers();
return Response.json(users);
},
};typescript
// routes/index.tsx
import { PageProps } from "$fresh/server.ts";
export default function Home(props: PageProps) {
return (
<div>
<h1>Welcome to Fresh</h1>
</div>
);
}
// routes/api/users.ts
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
async GET(_req, _ctx) {
const users = await getUsers();
return Response.json(users);
},
};Database Integration
数据库集成
typescript
// Using Deno KV (built-in key-value store)
const kv = await Deno.openKv();
// Set a value
await kv.set(["users", "1"], { name: "John", email: "john@example.com" });
// Get a value
const result = await kv.get(["users", "1"]);
console.log(result.value);
// List values
const entries = kv.list({ prefix: ["users"] });
for await (const entry of entries) {
console.log(entry.key, entry.value);
}typescript
// 使用Deno KV(内置键值存储)
const kv = await Deno.openKv();
// 设置值
await kv.set(["users", "1"], { name: "John", email: "john@example.com" });
// 获取值
const result = await kv.get(["users", "1"]);
console.log(result.value);
// 列出值
const entries = kv.list({ prefix: ["users"] });
for await (const entry of entries) {
console.log(entry.key, entry.value);
}Environment Variables
环境变量
typescript
// Access environment variables (requires --allow-env)
const apiKey = Deno.env.get("API_KEY");
// Using dotenv
import { load } from "https://deno.land/std/dotenv/mod.ts";
const env = await load();typescript
// 访问环境变量(需要--allow-env权限)
const apiKey = Deno.env.get("API_KEY");
// 使用dotenv
import { load } from "https://deno.land/std/dotenv/mod.ts";
const env = await load();Testing with Built-in Test Runner
使用内置测试运行器进行测试
typescript
// user_test.ts
import { assertEquals, assertRejects } from "https://deno.land/std/assert/mod.ts";
import { describe, it, beforeEach } from "https://deno.land/std/testing/bdd.ts";
import { getUser, createUser } from "./user_service.ts";
describe("User Service", () => {
beforeEach(() => {
// Setup
});
it("should create a user", async () => {
const user = await createUser({ name: "John", email: "john@example.com" });
assertEquals(user.name, "John");
});
it("should throw for invalid email", async () => {
await assertRejects(
() => createUser({ name: "John", email: "invalid" }),
Error,
"Invalid email"
);
});
});
// Run tests
// deno test --allow-net --allow-readtypescript
// user_test.ts
import { assertEquals, assertRejects } from "https://deno.land/std/assert/mod.ts";
import { describe, it, beforeEach } from "https://deno.land/std/testing/bdd.ts";
import { getUser, createUser } from "./user_service.ts";
describe("User Service", () => {
beforeEach(() => {
// 初始化设置
});
it("should create a user", async () => {
const user = await createUser({ name: "John", email: "john@example.com" });
assertEquals(user.name, "John");
});
it("should throw for invalid email", async () => {
await assertRejects(
() => createUser({ name: "John", email: "invalid" }),
Error,
"Invalid email"
);
});
});
// 运行测试
// deno test --allow-net --allow-readBuilt-in Tooling
内置工具
bash
undefinedbash
undefinedFormatting
代码格式化
deno fmt
deno fmt
Linting
代码检查
deno lint
deno lint
Type checking
类型检查
deno check main.ts
deno check main.ts
Bundle
代码打包
deno bundle main.ts bundle.js
deno bundle main.ts bundle.js
Compile to executable
编译为可执行文件
deno compile --allow-net main.ts
deno compile --allow-net main.ts
Documentation generation
文档生成
deno doc main.ts
deno doc main.ts
Dependency inspection
依赖检查
deno info main.ts
undefineddeno info main.ts
undefinedConfiguration with deno.json
使用deno.json配置
json
{
"tasks": {
"dev": "deno run --watch --allow-net --allow-env main.ts",
"start": "deno run --allow-net --allow-env main.ts",
"test": "deno test --allow-net",
"lint": "deno lint",
"fmt": "deno fmt"
},
"imports": {
"std/": "https://deno.land/std@0.208.0/",
"@/": "./src/"
},
"compilerOptions": {
"strict": true,
"lib": ["deno.window"]
},
"lint": {
"rules": {
"tags": ["recommended"]
}
},
"fmt": {
"indentWidth": 2,
"singleQuote": true
}
}json
{
"tasks": {
"dev": "deno run --watch --allow-net --allow-env main.ts",
"start": "deno run --allow-net --allow-env main.ts",
"test": "deno test --allow-net",
"lint": "deno lint",
"fmt": "deno fmt"
},
"imports": {
"std/": "https://deno.land/std@0.208.0/",
"@/": "./src/"
},
"compilerOptions": {
"strict": true,
"lib": ["deno.window"]
},
"lint": {
"rules": {
"tags": ["recommended"]
}
},
"fmt": {
"indentWidth": 2,
"singleQuote": true
}
}Error Handling
错误处理
typescript
class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public code: string = "INTERNAL_ERROR"
) {
super(message);
this.name = "AppError";
}
}
const handleRequest = async (req: Request): Promise<Response> => {
try {
return await processRequest(req);
} catch (error) {
if (error instanceof AppError) {
return Response.json(
{ error: error.message, code: error.code },
{ status: error.statusCode }
);
}
console.error(error);
return Response.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
};typescript
class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public code: string = "INTERNAL_ERROR"
) {
super(message);
this.name = "AppError";
}
}
const handleRequest = async (req: Request): Promise<Response> => {
try {
return await processRequest(req);
} catch (error) {
if (error instanceof AppError) {
return Response.json(
{ error: error.message, code: error.code },
{ status: error.statusCode }
);
}
console.error(error);
return Response.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
};Web Standards
Web标准
Deno embraces web standards. Use:
- for HTTP requests
fetch() - and
RequestobjectsResponse - and
URLURLSearchParams - for cryptography
Web Crypto API - for data streaming
Streams API - for multipart data
FormData
Deno拥抱Web标准,建议使用:
- 发起HTTP请求
fetch() - 和
Request对象Response - 和
URLURLSearchParams - 进行加密操作
Web Crypto API - 处理数据流
Streams API - 处理多部分数据
FormData
Performance
性能优化
- Use web streams for large data processing
- Leverage Deno KV for fast key-value storage
- Use for high-performance HTTP
Deno.serve - Compile to standalone executables for deployment
- 处理大数据时使用Web Streams
- 利用Deno KV实现快速键值存储
- 使用搭建高性能HTTP服务
Deno.serve - 编译为独立可执行文件进行部署