2026-10-23 16:31:00
TypeScript 的附加特性主要包括装饰器、类型声明文件(.d.ts)、declare 关键字、类型操作符、tsconfig.json 配置、tsc 命令行工具,以及一些高级类型和语法特性。以下是对这些特性的详细说明:
1. 装饰器(Decorators)装饰器是一种特殊类型的声明,它能够被附加到类声明、方法、属性或参数上,以修改类的行为。装饰器使用 @ 符号作为前缀,并且必须是一个函数或者执行后可以得到一个函数的表达式。
装饰器的结构type Decorator = ( value: DecoratedValue, context: { kind: string; name: string | symbol; addInitializer?(initializer: () => void): void; static?: boolean; private?: boolean; access: { get?(): unknown; set?(value: unknown): void; }; }) => void | ReplacementValue;装饰器的种类类型声明文件用于为 JavaScript 代码提供类型信息,使得 TypeScript 能够理解 JavaScript 代码的结构和类型。
declare 关键字declare 关键字用于告诉 TypeScript 编译器某个变量、类型、类、函数等是存在的,即使它们在当前文件中没有定义。
// declare variabledeclare let x: number;declare let x;declare var document;document.title = "Hello";// declare functiondeclare function sayHello(name: string): void;sayHello('张三');// declare classdeclare class C { public static s0(): string; private static s1: string; public a: number; private b: number; constructor(arg: number); m(x: number, y: number): number; get c(): number; set c(value: number); [index: string]: any;}// declare module, declare namespacedeclare namespace AnimalLib { class Animal { constructor(name: string); eat(): void; sleep(): void; } type Animals = 'Fish' | 'Dog';}// 或者declare module AnimalLib { class Animal { constructor(name: string); eat(): void; sleep(): void; } type Animals = 'Fish' | 'Dog';}// declare globalexport {};declare global { interface String { toSmallString(): string; }}String.prototype.toSmallString = (): string => { return '';};// declare enumdeclare enum E1 { A, B,}declare enum E2 { A = 0, B = 1,}declare const enum E3 { A, B,}declare const enum E4 { A = 0, B = 1,}declare moduledeclare module 用于为外部模块提供类型声明。
// node.d.tsdeclare module "url" { export interface Url { protocol?: string; hostname?: string; pathname?: string; } export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;}declare module "path" { export function normalize(p: string): string; export function join(...paths: any[]): string; export var sep: string;}3. 类型操作符TypeScript 提供了一些类型操作符,用于在类型系统中进行高级操作。
keyof 运算符keyof 运算符用于获取一个类型的所有键的联合类型。
interface Person { name: string; age: number;}type PersonKeys = keyof Person; // "name" | "age"in 运算符in 运算符用于遍历联合类型。
type Keys = 'a' | 'b' | 'c';type Obj = { [K in Keys]: number;};// 等价于// type Obj = {// a: number;// b: number;// c: number;// }方括号运算符方括号运算符用于访问类型的属性。
interface Person { name: string; age: number;}type NameType = Person['name']; // stringextends…?: 条件运算符extends…?: 条件运算符用于根据条件进行类型判断。
type IsString<T> = T extends string ? true : false;type A = IsString<string>; // truetype B = IsString<number>; // falseinfer 关键字infer 关键字用于在条件类型中推断类型。
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;type Func = () => number;type FuncReturnType = ReturnType<Func>; // numberis 运算符is 运算符用于类型谓词,用于在运行时检查类型。
function isString(value: any): value is string { return typeof value === 'string';}function doSomething(value: any) { if (isString(value)) { console.log(value.toUpperCase()); // value 是 string 类型 }}4. 模板字符串类型模板字符串类型用于基于模板字符串字面量类型创建新的字符串字面量类型。
type World = "world";type Greeting = `hello ${World}`; // "hello world"5. 映射类型映射类型用于基于旧类型创建新类型。
type Readonly<T> = { readonly [P in keyof T]: T[P];};interface Person { name: string; age: number;}type ReadonlyPerson = Readonly<Person>;// 等价于// type ReadonlyPerson = {// readonly name: string;// readonly age: number;// }6. 注释指令TypeScript 支持一些注释指令,用于提供额外的类型信息。
JSDocJSDoc 注释用于提供类型信息。
/ * @typedef {Object} Person * @property {string} name * @property {number} age *// * @type {Person} */const person = { name: '张三', age: 30 };@typedef@typedef 用于定义类型别名。
/ * @typedef {Object} Person * @property {string} name * @property {number} age */@type@type 用于指定变量的类型。
/ * @type {string} */const name = '张三';@param@param 用于指定函数参数的类型。
/ * @param {string} name */function greet(name) { console.log(`Hello, ${name}!`);}@return, @returns@return 或 @returns 用于指定函数的返回类型。
/ * @returns {string} */function getGreeting() { return 'Hello!';}@extends 和类型修饰符@extends 用于指定类继承的类型。
/ * @extends {BaseClass} */class MyClass extends BaseClass {}7. tsconfig.jsontsconfig.json 文件用于配置 TypeScript 编译器的行为。
{ "compilerOptions": { "target": "ES6", "module": "commonjs", "strict": true, "esModuleInterop": true }, "include": ["src//*"], "exclude": ["node_modules"]}8. tsc 命令tsc 是 TypeScript 编译器的命令行工具,用于编译 TypeScript 代码。
基本用法tsc file.ts常用参数TypeScript 支持 ES6 中的一些类型,如 Map。
const map = new Map<string, number>();map.set('a', 1);map.set('b', 2);console.log(map.get('a')); // 110. async 函数async 函数用于处理异步操作。
async function fetchData() { const response = await fetch('Generator 函数用于生成迭代器。
function* generateNumbers() { yield 1; yield 2; yield 3;}const generator = generateNumbers();console.log(generator.next().value); // 1console.log(generator.next().value); // 2console.log(generator.next().value); // 312. React 和 JSX 语法TypeScript 支持 React 和 JSX 语法。
import React from 'react';interface Props { name: string;}class Greeting extends React.Component<Props> { render() { return <h1>Hello, {this.props.name}</h1>; }}// 或者函数组件const Greeting: React.FC<Props> = ({ name }) => <h1>Hello, {name}</h1>;13. React 库内置元素组件的写法在 TypeScript 中,React 的内置元素组件可以通过 React.FC 或 React.Component 来定义。
import React from 'react';interface ButtonProps { onClick: () => void; children: React.ReactNode;}const Button: React.FC<ButtonProps> = ({ onClick, children }) => ( <button onClick={onClick}>{children}</button>);// 或者类组件class Button extends React.Component<ButtonProps> { render() { return <button onClick={this.props.onClick}>{this.props.children}</button>; }}总结TypeScript 的附加特性包括装饰器、类型声明文件、declare 关键字、类型操作符、tsconfig.json 配置、tsc 命令行工具,以及一些高级类型和语法特性。这些特性使得 TypeScript 能够提供更强大的类型检查和更丰富的开发体验。