← 返回完整题库
Typescript简单

TypeScript中的 Declare 关键字有什么用?

参考答案

作用

declare 用于类型声明(ambient declaration):告诉 TS "某个变量/函数/模块/类在运行时存在,但类型信息由我来描述",编译器据此做类型检查,不会生成任何运行时代码。

常见用法

  1. 声明全局变量/函数(如 CDN 注入的 window.jQuery):
declare const VERSION: string;
declare function greet(name: string): void;
declare let counter: number;
  1. 声明模块(给没有类型的 JS 库补类型):
declare module 'some-lib' {
  export function doSomething(x: number): string;
  const def: { a: number };
  export default def;
}
// 或者只需"能 import 但不检查"
declare module '*.css';
declare module '*.png' { const src: string; export default src; }
  1. 声明命名空间/全局扩展:
declare namespace MyLib { function fn(): void; }
declare global {
  interface Window { __APP_CONFIG__: Record<string, string> }
}
  1. 声明类(只描述形状):
declare class Animal { name: string; constructor(name: string); speak(): void; }
  1. 模块增强(module augmentation):在已有模块上扩展类型
declare module 'express-serve-static-core' {
  interface Request { user?: User }
}

要点

  • declare 只存在于类型空间,编译后被完全擦除,绝不产生 JS。
  • 通常写在 .d.ts 文件里;.ts 里也能写,但要注意 declare global 必须位于模块文件内。
  • 与 declare var/let/const 区别:var/let 可重新赋值,const 表示不可变绑定。
  • 与 type/interface 声明不同:declare 描述的是运行时已存在的值。
  • 与 declare module 的"通配声明"配合可解决"找不到模块声明"的报错。

与 .d.ts 的关系

.d.ts 是"只含类型声明"的文件,declare 是其中最常用的关键字;发布库时通过 "types" 字段或 declaration: true 自动生成,供使用方获得类型提示。

本题来自 计算机知识面试题库,共 921 道题。