-
类型:
类型 例子 描述 number 1, -33, 2.5 任意数字 string ‘hi’, “hi”, hi
任意字符串 boolean true、false 布尔值true或false 字面量 其本身 限制变量的值就是该字面量的值 any * 任意类型 unknown * 类型安全的any void 空值(undefined) 没有值(或undefined) never 没有值 不能是任何值,只能抛出异常 object {name:‘孙悟空’} 任意的JS对象 array [1,2,3] 任意JS数组 tuple [4,5] 元素,TS新增类型,固定长度数组 enum enum{A, B} 枚举,TS中新增类型 -
用法
-
number
typescript">let decimal: number = 6; let hex: number = 0xf00d; let big: bigint = 100n;
-
boolean
typescript">let isDone: boolean = false;
-
string
typescript">let color: string = "blue"; color = 'red';
-
字面量
-
也可以使用字面量去指定变量的类型,通过字面量可以确定变量的取值范围
typescript">let color: 'red' | 'blue' | 'black'; let num: 1 | 2 | 3 | 4 | 5;
-
any
typescript">let d: any = 4; d = 'hello'; d = true;
-
unknown
typescript">let notSure: unknown = 4; notSure = 'hello';
-
void
typescript">let unusable: void = undefined; function fn(): void{} function fn(): void {return undefined }
-
never
typescript">function error(message: string): never {throw new Error(message); }
-
object(没啥用)
typescript">let obj: object = {};
-
array
typescript">let list: number[] = [1, 2, 3]; let list: Array<number> = [1, 2, 3];
-
tuple
typescript">let x: [string, number]; x = ["hello", 10];
-
enum
typescript">enum Color {Red, // 0Green, // 1Blue, // 2 } let c: Color = Color.Green;enum Color {Red = 1, // 1Green, // 2Blue, // 3 } let c: Color = Color.Green;enum Color {Red = 1, // 1Green = 2, // 2Blue = 4, // 4 } let c: Color = Color.Green;
-
-
断言
//写法1let someValue: unknown = "this is a string";let strLength: number = (someValue as string).length;//写法2let someValue: unknown = "this is a string";let strLength: number = (<string>someValue).length;```
-
接口
- 接口的作用类似于没有实际值的抽象类
- 可以用于定义对象,方法的参数/返回值,接口(使用
extends
关键字),类(使用implements
关键字)的结构//对象 interface Info {name: stringage: numbersay?: () => void }const user: Info = {name: '张三',age: 18,say: () => {console.log(`我叫${this.name}`)} } //方法的参数和返回值 interface sum {(a: number, b: number): number }const add: sum = (a, b) => {return a + b; } sum(1, 2) // 接口 interface Person{name: string;say():void; } interface man extends Person{eat():void; } // 类 interface Person{name: string;say():void; } interface Student{hello():void; } // 同时执行多个接口,用`,`隔开 class Student implements Person,Student{constructor(public name: string) {}say() {console.log(`我叫${this.name}`);}hello() {console.log(`我是一个学生`);} }
-
Class (链接: link)
-
泛型(链接:link)