ts-code
TypeScript 语法大全与示例
基础类型
1. 原始类型
1 | let isDone: boolean = false; |
2. 数组
1 | let list1: number[] = [1, 2, 3]; |
3. 元组 (Tuple)
1 | let tuple: [string, number]; |
4. 枚举 (Enum)
1 | enum Color { |
5. Any 和 Unknown
1 | let notSure: any = 4; |
6. Never
1 | function error(message: string): never { |
7. 类型断言
1 | let someValue: any = "this is a string"; |
接口 (Interface)
1. 基础接口
1 | interface Person { |
2. 函数类型
1 | interface SearchFunc { |
3. 可索引类型
1 | interface StringArray { |
4. 类类型
1 | interface ClockInterface { |
类 (Class)
1. 基础类
1 | class Animal { |
2. 继承
1 | class Dog extends Animal { |
3. 存取器 (getter/setter)
1 | class Employee { |
4. 静态属性
1 | class Grid { |
5. 抽象类
1 | abstract class Department { |
函数
1. 函数类型
1 | function add(x: number, y: number): number { |
2. 可选参数和默认参数
1 | function buildName(firstName: string, lastName?: string) { |
3. 剩余参数
1 | function buildName3(firstName: string, ...restOfName: string[]) { |
4. 函数重载
1 | function pickCard(x: {suit: string; card: number}[]): number; |
泛型
1. 基础泛型
1 | function identity<T>(arg: T): T { |
2. 泛型接口
1 | interface GenericIdentityFn<T> { |
3. 泛型类
1 | class GenericNumber<T> { |
4. 泛型约束
1 | interface Lengthwise { |
高级类型
1. 交叉类型 (Intersection Types)
1 | interface Person { |
2. 联合类型 (Union Types)
1 | function padLeft(value: string, padding: string | number) { |
3. 类型别名 (Type Aliases)
1 | type Name = string; |
4. 字符串字面量类型
1 | type Easing = "ease-in" | "ease-out" | "ease-in-out"; |
5. 可辨识联合 (Discriminated Unions)
1 | interface Square { |
模块
1. 导出
1 | // math.ts |
2. 导入
1 | import { add, PI } from "./math"; |
3. 默认导出
1 | // calculator.ts |
装饰器 (Decorators)
1 | function sealed(constructor: Function) { |
实用工具类型
1. Partial
1 | interface Todo { |
2. Readonly
1 | interface Todo { |
3. Record
1 | interface PageInfo { |
4. Pick 和 Omit
1 | interface Todo { |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 小徐的博客!
评论