TypeScript的相关用法

1. TS定义数组类型的三种方式

1)类型

let arr: number[] = [1, 2, 3, 4] // 数字数组 不允许出现其他数据类型
 
let arr2: string[] = ['h', 'h', 'h'] // 字符串数组
 
let arr3: any[] = [1, 'h', 'h', 3] //允许数组中出现任意类型

2)Array 用数组泛型表示数组

  let arr: Array<string> = ['bonjour', 'hello']
  let arr2: Array<number> = [1, 2]
  let arr3: Array<any> = [1, 2, 'hh']

3)利用接口: ts的核心原则是对值所具有的结构进行类型检查,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约


interface NumberArray {
  // 这个接口表示:只要索引的类型是number,那么值的类型必须是number
  [index: number]: number;

2. TS 声明一个boolean, number, string类型的值

// 在js中,定义 isFlag 为true, 但是后面还可以重新给它赋值为字符串,而ts中就不行,同理,声明number, string 也一样
let bool: boolean = true;
// isFlag = "str"   // 会报错:不能将类型“"str"”分配给类型“boolean”。

let str: string = "a";
// str = 1   // 会报错:不能将类型“1”分配给类型“string”。

let num: number = 1;
// num = "a"  // 会报错:不能将类型“"a"”分配给类型“number”。
 

3. ts 声明一个 undefined, null 类型的值

let u: undefined = undefined;
let n: null = null;
 

4. 类型断言as,可以用来告诉解析器变量的实际类型

/*
* 语法:
*   变量 as 类型
*   <类型>变量
*
* */
s = e as string;
s = <string>e;

as any
只是想给window添加一个属性,但因为window上并没有a属性,所以报错。此时,就需要将window断言为any

window.a = "hello world";
//  Property 'a' does not exist on type 'Window & typeof globalThis'
// 正确写法
(window as any).a = "hello world";

不能滥用as any,也不能完全否定它的作用,需要在类型的严格性和开发的便利性之间掌握平衡。

5. void 用来表示空,以函数为例,就表示没有返回值的函数

function fn(): void{
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值