You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在TypeScript中引入环境变量的正确方式是什么?

Proper Ways to Type Cloudflare Workers Environment Variables in TypeScript

Hey there! I’ve dealt with this exact frustration before—those quick fixes (JS shims or @ts-ignore) work in a pinch but leave you without TypeScript’s safety net. Here are the clean, TypeScript-native solutions for Cloudflare Workers (since you’re using wrangler):

1. Extend the Global Env Interface

Cloudflare Workers’ TypeScript definitions include a global Env interface that you can extend to define your environment variables. This tells TypeScript exactly what variables exist and their types.

Step 1: Create a Type Declaration File

Make a file like env.d.ts in your project root:

declare global {
  interface Env {
    // Add your variables here with their correct types
    SOMEVAR: string;
    API_KEY: string;
    MAX_REQUESTS: number;
  }
}

// This export ensures the file is treated as a module
export {};

Step 2: Use the Env Object in Your Worker

In your main Worker file (e.g., index.ts), you’ll receive the env parameter directly from the fetch handler—TypeScript will now recognize your variables:

export default {
  async fetch(request: Request, env: Env) {
    // No more TS errors here!
    console.log("Using SOMEVAR:", env.SOMEVAR);
    console.log("Max requests allowed:", env.MAX_REQUESTS);

    return new Response("Hello from Worker!");
  },
};

2. Pass Env to Other Files (Dependency Injection)

If you need to access environment variables in helper functions or other modules, don’t rely on globals—pass the Env object explicitly. This keeps your code type-safe and testable.

Example helper function (utils.ts):

export function validateApiKey(env: Env, providedKey: string) {
  return providedKey === env.API_KEY;
}

Then use it in your main Worker:

import { validateApiKey } from "./utils";

export default {
  async fetch(request: Request, env: Env) {
    const authHeader = request.headers.get("Authorization");
    const isValid = validateApiKey(env, authHeader || "");

    return isValid 
      ? new Response("Authenticated!") 
      : new Response("Unauthorized", { status: 401 });
  },
};

Why Your Old Fixes Aren’t Ideal

  • process.env is a Node.js-specific feature—Cloudflare Workers run in a V8 isolate without Node’s API, so this won’t work.
  • @ts-ignore silences TypeScript’s checks, which means you might accidentally misspell a variable name or use the wrong type without catching it early.
  • JS shim files skip TypeScript’s type system entirely, losing all the benefits of using TS in the first place.

Quick Note on Wrangler Configuration

Make sure your variables are properly declared in wrangler.toml:

  • For public variables (non-secrets), use the [vars] section:
    [vars]
    SOMEVAR = "my-public-value"
    MAX_REQUESTS = "100" # Wrangler parses this as a string, so adjust your TS type if needed
    
  • For secrets (like API keys), use wrangler secret put API_KEY to set them—you don’t need to add them to wrangler.toml, but you still include them in the Env interface.

内容的提问来源于stack exchange,提问作者David Min

火山引擎 最新活动