一、接口: 一种约束
接口一般首字母大写
1、用接口描述对象:属性和属性值都可以约束
interface Person {
// 只读属性
readonly id: number,
// 对象属性名:对象属性值的类型
name: string,
// ?表示可有可无的属性
age?: number,
// 任意属性
[propName: number]: any,
[propName: string]: string | number | boolean | undefined
}
const p: Person = {
id: 1,
name: 'hello',
age: 12,
// 上面有任意属性,所以可以定义width、height和flex
width: '12px',
height: '30px',
flex: '1'
}
p.id = 3; // 报错,无法为“id”赋值,因为id是只读属性。
2、用接口描述数组:少用,仅作了解
interface IArray {
// [数组的索引: 索引的类型]: 数组元素的类型
[index: number]: number
}
const newArr: IArray = [1, 2, 3, "str"]; // 报错,不能将类型“string”分配给类型“number”
3、用接口描述函数
interface ISearchFunc {
// (参数1: 参数1的类型,参数2: 参数2的类型): 函数返回值的类型
(a: string, b: string): boolean
}
const func1: ISearchFunc = function (a: string, b: string): boolean {
return a.search(b) !== -1;
}
console.log(func1("typescript", "type")); // true
二、函数
1、ts对函数的完整写法
const myFunc1: (a: number, b: number) => boolean = function (a: number, b: number): boolean {
return a === b;
}
const result: boolean = myFunc1(1, 2);
console.log(result); // false
2、函数的可选参数和默认参数
// y参数是可选参数:可选参数不传参最后会得到undefined
// z参数带默认值
const myFunc2 = function (x: string, y?: string, z: string = "加油") {
return x + y + z;
}
console.log(myFunc2("大家")); // 大家undefined加油
3、函数的剩余参数
// ...rest: 数组元素的类型[]
const myFunc3 = function (x: string, y: string, ...rest: number[]) {
return rest;
}
// 1,2,3 是剩余参数
console.log(myFunc3("a", "b", 1, 2, 3)); // [ 1, 2, 3 ]
4、函数的重载
方法:为同一个函数提供多个函数类型定义来进行函数重载。 编译器会根据这个列表去处理函数的调用。
// 下面我们来重载 overLoadFunc 函数
function overLoadFunc(x: number, y: number): number
function overLoadFunc(x: string, y: string): string
// overLoadFunc方法根据传入参数的不同会返回两种不同的类型: number | string
function overLoadFunc(x: number | string, y: number | string): number | string {
if (typeof x === "number" && typeof y === "number") {
return x + y;
} else if (typeof x === "string" && typeof y === "string") {
return x + y;
}
return x;
}
console.log(overLoadFunc(1, 2)); // 3
console.log(overLoadFunc("a", "b")); // ab
三、类型断言
类型断言:手动指定类型
1、在函数内使用类型断言
方式一:(变量 as 类型)
方式二:(<类型>变量)
const myFunc4 = function (x: string | number): number {
// 在联合类型使用类型断言
// 方式一:(变量 as 类型)
// 方式二:(<类型>变量)
return (x as string).length ? (<string>x).length : x.toString().length;
}
console.log(myFunc4(123)); // 3
2、将any类型断言为具体类型
const myFunc5 = function (x: any, y: any): any {
return x + y;
}
// 可以使用类型断言把any类型断言为具体类型,把result5变为number类型
let result5 = myFunc5(1, 2) as number;
查看断言前的结果:
查看断言后的结果:
3、将任何一个类型断言为any类型
// 也可以将任何一个类型断言为any类型,any可以访问任何属性和方法
// 原则上不推荐使用any,不能滥用any,但是也不能否定any的作用,需要自己平衡
(window as any).a = "test";
四、类型别名
// s是string的别名
type s = string;
const testHi: s = 'hi';
// 别名通常用于联合类型
// all是 string | number | boolean 的别名
type all = string | number | boolean;
const testA1: all = true;
const testA2: all = 123;
五、字符串字面量类型
type stringType = "ts" | "vue" | "vite" | "pinia"
// 取值只能取stringType字符串里面的一个
const testStr: stringType = "pinia";
写代码时可以直接选择字面量的类型: