TypeScript篇:Typescript附加特性

TypeScript篇:Typescript附加特性
最新回答
蝶舞╰︶櫻婲落ペ

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;装饰器的种类
  • 类装饰器:应用于类构造函数。
  • 方法装饰器:应用于方法。
  • 属性装饰器:应用于属性。
  • getter/setter 装饰器:应用于 getter 或 setter 方法。
  • accessor 装饰器:应用于访问器。
示例// 类装饰器function Greeter(value, context) { if (context.kind === 'class') { value.prototype.greet = function () { console.log('你好'); }; }}@Greeterclass User {}let u = new User();u.greet(); // "你好"// 方法装饰器class Person { name: string; constructor(name: string) { this.name = name; } @log greet() { console.log(`Hello, my name is ${this.name}.`); }}function log(originalMethod: any, context: ClassMethodDecoratorContext) { const methodName = String(context.name); function replacementMethod(this: any, ...args: any[]) { console.log(`LOG: Entering method '${methodName}'.`); const result = originalMethod.call(this, ...args); console.log(`LOG: Exiting method '${methodName}'.`); return result; } return replacementMethod;}const person = new Person('张三');person.greet();// "LOG: Entering method 'greet'."// "Hello, my name is 张三."// "LOG: Exiting method 'greet'."// 属性装饰器function logged(value, context) { const { kind, name } = context; if (kind === 'field') { return function (initialValue) { console.log(`initializing ${name} with value ${initialValue}`); return initialValue; }; }}class Color { @logged name = 'green';}const color = new Color();// "initializing name with value green"// getter/setter 装饰器class C { @lazy get value() { console.log('正在计算……'); return '开销大的计算结果'; }}function lazy(value: any, { kind, name }: any) { if (kind === 'getter') { return function (this: any) { const result = value.call(this); Object.defineProperty(this, name, { value: result, writable: false, }); return result; }; } return;}const inst = new C();inst.value;// 正在计算……// '开销大的计算结果'inst.value;// '开销大的计算结果'2. 类型声明文件(.d.ts)

类型声明文件用于为 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 module

declare 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 支持一些注释指令,用于提供额外的类型信息。

JSDoc

JSDoc 注释用于提供类型信息。

/ * @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.json

tsconfig.json 文件用于配置 TypeScript 编译器的行为。

{ "compilerOptions": { "target": "ES6", "module": "commonjs", "strict": true, "esModuleInterop": true }, "include": ["src//*"], "exclude": ["node_modules"]}8. tsc 命令

tsc 是 TypeScript 编译器的命令行工具,用于编译 TypeScript 代码。

基本用法tsc file.ts常用参数
  • --watch:监视文件变化并重新编译。
  • --project 或 -p:指定 tsconfig.json 文件。
  • --outDir:指定输出目录。
  • --module:指定模块系统。
  • --target:指定 ECMAScript 目标版本。
9. ES6 类型

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('
https://api.example.com/data'
); const data = await response.json(); return data;}fetchData().then(data => console.log(data));11. Generator 函数

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 能够提供更强大的类型检查和更丰富的开发体验。