Global type definition
Basic Concepts of Global Type Definitions
Global type definitions allow types to be used across files in a TypeScript project without explicit imports. This mechanism is particularly suitable for large projects or scenarios where type definitions need to be shared. Global type definitions are typically implemented using .d.ts
declaration files, which contain only type declarations and no concrete implementations.
// types/global.d.ts
declare namespace MyGlobal {
interface User {
id: number;
name: string;
email: string;
}
}
Creation and Usage of Declaration Files
Creating global type definitions requires following specific rules. Declaration files must have the .d.ts
extension and are usually placed in the project's type definition directory. TypeScript automatically recognizes type declarations in these files.
// src/utils.ts
function getUser(): MyGlobal.User {
return { id: 1, name: 'Alice', email: 'alice@example.com' };
}
Global Interfaces and Types
Interfaces and type aliases can be defined in the global scope. These definitions are available throughout the project without import statements, making them particularly useful for core application models.
// types/global.d.ts
interface Product {
sku: string;
price: number;
inventory: number;
}
type DiscountStrategy = (price: number) => number;
Extending Global Namespaces
Global namespaces can be extended using declaration merging. This technique is often used to add type definitions for third-party libraries or to extend existing global interfaces.
// types/global.d.ts
declare namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'development' | 'production' | 'test';
API_URL: string;
}
}
Global Variable Declarations
When certain variables need to be accessed in the global scope, their types can be declared using declare var
, declare let
, or declare const
.
// types/global.d.ts
declare const __VERSION__: string;
declare let DEBUG: boolean;
// src/app.ts
if (DEBUG) {
console.log(`App version: ${__VERSION__}`);
}
Global Function Declarations
Globally available functions can also be defined in declaration files. This is particularly useful for utility functions used across multiple modules.
// types/global.d.ts
declare function formatCurrency(value: number, currency?: string): string;
// src/components/Price.tsx
const priceDisplay = formatCurrency(99.99, 'USD');
Global Enum Definitions
Although enums in TypeScript typically have module scope, they can be made available throughout the project via global declarations.
// types/global.d.ts
declare enum LogLevel {
Error,
Warn,
Info,
Debug
}
// src/logger.ts
function log(message: string, level: LogLevel = LogLevel.Info) {
// Implementation omitted
}
Global Class Declarations
Global class declarations allow class types to be used without imports. This is helpful for core class definitions in frameworks or libraries.
// types/global.d.ts
declare class Observable<T> {
subscribe(observer: (value: T) => void): void;
unsubscribe(observer: (value: T) => void): void;
next(value: T): void;
}
// src/store.ts
const userObservable = new Observable<MyGlobal.User>();
Global Module Augmentation
Module augmentation techniques can be used to add global type definitions to existing modules. This is particularly useful for extending types of third-party modules.
// types/global.d.ts
import { Vue } from 'vue/types/vue';
declare module 'vue/types/vue' {
interface Vue {
$myGlobalMethod: (arg: string) => void;
}
}
Interaction Between Global Types and Module Systems
When using both global types and module systems, it's important to be aware of scope rules. Types in modules have module scope by default unless explicitly exported.
// types/global.d.ts
declare module '*.svg' {
const content: string;
export default content;
}
// src/components/Icon.tsx
import logo from './logo.svg'; // Type automatically inferred as string
Best Practices for Global Type Definitions
Organizing global type definitions requires following certain conventions. It's generally recommended to centralize global types and group them by feature or domain.
// types/global.d.ts
declare namespace App {
namespace Models {
interface Post {
id: number;
title: string;
content: string;
}
}
namespace Services {
interface ApiResponse<T> {
data: T;
status: number;
}
}
}
Testing and Validation of Global Type Definitions
Ensuring global type definitions work correctly requires type checking. This can be done by creating test files or using the TypeScript compiler for validation.
// test/globalTypes.test.ts
const testUser: MyGlobal.User = {
id: 1,
name: 'Test',
email: 'test@example.com'
// Missing the email property will cause a type error
};
Global Types and Third-Party Libraries
When integrating third-party libraries, global type definitions can help simplify type management, especially for libraries that don't provide their own type definitions.
// types/global.d.ts
declare module 'legacy-library' {
export function doSomething(config: {
timeout?: number;
retries?: number;
}): Promise<void>;
}
// src/app.ts
import { doSomething } from 'legacy-library';
doSomething({ timeout: 1000 });
Limitations of Global Type Definitions
While global types are convenient, they have limitations. Overuse can lead to naming conflicts and make type definitions difficult to track.
// types/global.d.ts
declare interface Window {
myApp: {
version: string;
init: () => void;
};
}
// If multiple declaration files extend the Window interface, conflicts may arise
The Role of Global Types in Modern TypeScript Projects
With the evolution of module systems, the use of global types has decreased, but they remain indispensable in certain scenarios, particularly for configuration types and environment variable definitions.
// types/global.d.ts
declare module 'config' {
export const apiEndpoint: string;
export const featureFlags: {
newDashboard: boolean;
darkMode: boolean;
};
}
// src/api.ts
import { apiEndpoint } from 'config';
fetch(`${apiEndpoint}/users`);
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:类型声明文件(.d.ts)
下一篇:模块扩充