跳转到主要内容
eLearner.app
模块 7 · 第 2 课(共 2)课程中的14/14~15 min
模块课程(2/2)

声明和合并

Type declaration files (with .d.ts extension) are used in TypeScript to describe the shape of existing JavaScript code without implementing any actual logic. They contain only type definitions, interfaces, and function signatures.

These files are essential when using third-party libraries written in pure JavaScript.


Declaration Merging

Declaration Merging is a behavior where the compiler merges two or more separate declarations declared with the same name into a single definition.

The most common case is interface merging:

TS
interface User {
  name: string;
}

interface User {
  age: number;
}

// The resulting User interface has both name and age properties!
const student: User = {
  name: 'Alice',
  age: 23,
};

If properties share the same name, they must be of the same type, otherwise TypeScript will report an error.


Modifying Global and External Modules

We can use declaration merging to extend interfaces defined in other modules or in the global scope.

For example, if we want to add a property to the browser's global window object:

TS
declare global {
  interface Window {
    analyticsToken: string;
  }
}

By using declare global, we tell TypeScript that we are injecting a new signature into the existing global Window interface.


Try it yourself

Exercise 1: Basic Declaration Merging

锻炼#ts.m7.l2.e1
尝试:0加载中...

In TypeScript, interfaces with the same name in the same scope are automatically merged. Declare an interface User with property name: string, then in a second block declare the same interface User adding the property age: number. Finally, declare a constant user of type User with appropriate values.

正在加载编辑器...
显示提示

Declare interface User twice, inserting the respective properties, and then assign the fields to the user object.

3 次尝试后可用的解决方案

Exercise 2: Extending the Global Window Interface

锻炼#ts.m7.l2.e2
尝试:0加载中...

Imagine you want to extend the global Window interface to add a custom property named config of type Record<string, string>. Write the correct declaration using declare global to merge the new property into the global Window interface.

正在加载编辑器...
显示提示

Use declare global { interface Window { config: Record<string, string>; } }.

3 次尝试后可用的解决方案