1.typeScript定义
TypeScript是一种编程语言。它是JavaScript的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程。
2.ts的优势
使用静态类型,对于不标准的数据类型参数直接给出错误提示,方便debug。
关于引入基于类的面向对象编程方面,则是引入了接口概念,方便类型检查。
3.接口
使用接口后对象只会保留接口需要的属性
对于对象字面量参数,会经过 额外属性检查,当将它们赋值给变量或作为参数传递的时候。 如果一个对象字面量存在任何“目标类型”不包含的属性时,你会得到一个错误。
简单来说就是对象字面量如果有接口不存在的子对象时,会报错。
绕开这些检查非常简单。 最简便的方法是使用类型断言:
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
函数接口:
//表示该函数接受两个string类型参数,返回值必须为boolean
//函数接口是函数声明时用的,放在fun()后面的是返回值接口
interface SearchFunc {
(source: string, subString: string): boolean;
}
4.可索引的类型
表示带有任意数量的数字索引的string类型属性
但是数字索引的返回值必须是字符串索引返回值类型的子类型,因为数组索引也会转换成字符索引,两者返回值需要保持一致
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
5.可选参数
要么指定其为可选参数,要么设置默认值,不能一起用
如果要跳过前面的参数,只要前面的参数穿undefind就行了
6.装饰器
装饰器分很多种
比如类装饰器就可以对类进行一些属性添加
代码如下:
function logClz(params:any) {
console.log(params) // class HttpClient
params.prototype.url = 'xxxx';
params.prototype.run = function() {
console.log('run...');
};
}
@logClz
class HttpClient {
constructor() {
}
}
var http:any = new HttpClient();
http.run(); // run...
或者装饰器工厂
function logClz(params:string) {
console.log('params:', params); //params: hello
return function(target:any) {
console.log('target:', target); //target: class HttpClient
target.prototype.url = 'xxxx';
target.prototype.run = function() {
console.log('run...');
};
}
}
@logClz('hello')
class HttpClient {
constructor() {
}
}
7.as
相当于强转,当你比ts更知道对象是不是某一类型时使用
8.is
类型防护,相当于该方法返回值为true时认为参数就是对应类型的
function isFish(pet: any): pet is Fish {
return (pet as Fish).swim !== undefined;
}
9.字面量赋值和对象赋值
字面量要求更高,要求一一匹配
对象赋值可以使用类似解析赋值的功能,只提取需要部分
10.pick、omit、exclude
exclude 接受类型数组,返回类型数组
pick 接受接口,返回接口
omit 接受接口,返回接口,用了exclude完成反向pick
11.可选链操作符
const a = this.props?.z;
// 含义:a = props.z或者undifined(当!this.props时,不报错,而是用空值
12.空值合并运算符
空值合并运算符(??)是一个逻辑运算符。当左侧操作数为 null 或 undefined 时,其返回右侧的操作数。否则返回左侧的操作数。
// 这可以避免传入undifinded
sendFieldToServer(textField?.text ?? '')
13.常用
export interface UserListItem {
id: number;
userId: number;
email: string;
mobile: string;
description: string;
status: number;
sex: number;
}
// 将参数变为可选
export type a = Partial<UserListItem>;
// 将可选变为必选
export type b = Required<a>;
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
// 同时规定key和value
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
interface Todo {
title: string;
description: string;
completed: boolean;
}
// 就是pick
type TodoPreview = Pick<Todo, "title" | "completed">;
// 反向pick
type TodoPreview2 = Omit<Todo, "description">;
type MessageOf<T extends { message: unknown }> = T["message"];
interface Email {
message: string;
}
type EmailMessageContents = MessageOf<Email>;
// infer就是表示一个待推断的值的类型
type GetReturnType<Type> = Type extends () => infer Return ? Return : never;
type Num = GetReturnType<() => number>;
// 获得返回值类型,内部用infer实现
type Bools2 = ReturnType<(a: boolean, b: boolean) => null>;