注:持续编辑状态
接口、类型 、声明
- 函数声明
declare function f1(): {a: number; b:number}
interface LabelledValue {
label: string; // 必选
color?: string; // 非必选
readonly x: number; // 只读
a: number[];
b: ReadonlyArray<number>;
[propName: string]: any; // 带有任意数量的其他属性
(source: string, subString: string): boolean; // 函数类型
}
类(class)
extends implements
泛型(interface)
类型(type)
keyof
汇总对象的key\
type Point = {x:number,y:numver}
type P = keyof Point // type P = 'x' | 'y'
type Arrayish = {[n:number]:unknow}
type A = ketof Arrayish // type A = number
// 特殊情况
type Mapish = {[key:string]:boolean}
type M = keyof Mapish // type M = string | number
typeof
let s = 'hello'
let n: = typeof s // n:string
typeof Predicate = (x:unknow) => boolean
typeof K = ReturnType<Predicate> // type k = boolean
// 如果function没有写return的类型,不能直接用 ReturnType ,会报错
function f() {
return {x:10,y:3}
}
typef P = ReturnType<f> // error: `'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?`
// 替代方式
type P = ReturnType<typeof f> // type P = { x:number, y: number }
索引访问类型 Indexed Access Types
条件类型 Conditional Types
映射类型 Mapped Types
模板字面量类型 Template Literal Types
枚举
高级类型
- 交叉类型 Intersection Types &
- 联合类型 Union types |
- 可辨识联合 Discirminated Unions
Unility Types(工具类型)
是TS内置的泛型类型,避免重复写“类型变换逻辑”,分为两类:
- 同态工具类型:仅基于输入类型的已有属性做变换(不新增属性)
- 非同态工具类型:不依赖输入类型的已有属性,直接创建全新类型
| 工具类型 | 语法示例 | 核心功能 | 同态、非同态 |
|---|---|---|---|
| Partial | Partial | 将T中所有第一层属性设为可选(?) | 同态 |
| Readonly | Readonly | 将T中所有第一层属性设为只读 | 同态 |
| Required | Required | 将T中的所有可选属性转为必选(移除?) | 同态 |
| Pick<T,K> | Pick<ModelProps,"id" | "name"> | 从T中保留指定属性K,生成新类型 | 同态 |
| Omit<T,K> | Omit<Todo, "a" | "b"> | 从T中排除指定属性K。保留其他属性 | 同态 |
| Record<K,T> | Record<CatName, CatInfo> | 创建键为K类型,值为T类型的全新键值对类型 | 非同态 |
| ReturnType | ReturenType 推到函数T的返回值类型 | 非同态 | |
| Parameters | Parameters | 推导函数 T 的参数类型数组(返回 [param1Type, param2Type,...]) | 非同态 |
| Awaited | Awaited<Promise> | 解包 Promise 类型(提取 Promise<T> 中的 T) | 非同态 |
| Extract<T,U> | Extract<Shape,{kind: "circle"}> | 从联合类型T 中** 提取**与 U 重叠的类型 | 同态 |
| Exclude<T,U> | Exclude<Shape,{kind: "circle"}> | 从联合类型 T 中排除与 U 重叠的类型 | 同态 |
| NoNullable | NoNullable<string[] | null|undefined> | 同态 | 从 T 中排除 null/undefined |
| InstanceType | InstanceType | 推导类 T 的实例类型 | 非同态 |
minxin 混入
- implements 用于让类遵守接口定义的“契约”,只约束结构,不提供实现,若类没有实现接口的所有成员,ts会报错。
- minxin :是复用,直接把逻辑复制到目标类。
// 1\基础混入类
class Animatable {
rotationSpeed: number: 0.01;
animate(){
console.log('test)
}
}
// 封装mixin工具函数
function applyMixin(T extends new (...args: any[])=>{}<>)(base: T, minxins: Array<new (...args: any[])=>{}>){
minxins.forEach(mixin=>{
Object.getOwnPertyNames(minxin.prototype).forEach(name=>{
if(name!=='constructor'){
base.prototype[name] = mixin.prototype[name]
}
})
})
return base
}
// 3\目标类,并应用mixin
class ThreeJScude {
color: string = 'green'
}
// 把Animatable的功能混入到ThreeJSCude
const AnumatedCude = applyMixin(ThreeJScude, [Animatable])
命名空间
namespace