2.typescript类型的高级用法(上)

1.类型别名

type Point = {
    x:number,
    y:number
}
function printXY(point:Point){
    console.log(point.x,point.y)
}
printXY({x:12,y:22})
---------------
type Id = number | string
functiob myId(id:Id){
    console.log(id)
}

2.类型断言:类型的声明和转换(和编译器做了一个告知交流)

有时候TS无法获取具体的类型信息,这个我们需要使用类型断言(Type Assertion)

  • 尖括号形式
let anyValue: any = 'hi xiaobai';
let anyLength: number = (<string>anyValue).length;
  • as声明
    比如我们通过document.getElementById,TS只知道该函数会返回HTMLElement,但不知道它具体的类型:
const myEl = document.getElementById("my-img") as HTMLImageElement
myEl.src = "图片地址"

TS只允许类型断言转换为更具体或者不太具体的类型版本,此规则可防止不可能的强制转换:

const name = "xiaobai" as number //x
const name = ("xiaobai" as unknown) as number

3.非空类型断言!

当我们编写下面的代码时,在执行ts的编译阶段会报错:
这是因为传入的message有可能是为undefined,这个时候方法是不能被执行的;

function printMessage(message?:string){
	//error:Object is possibly 'undefined'
	console.log(message.toUpperCase())
}

但是,我们确定传入的参数是有值的,这个时候我们可使用非空类型断言:
非空类型断言使用的是!,表示可以确定某个标识符是有值的,跳过ts的编译时检测;

function printMessage(message?:string){
	console.log(message!.toUpperCase())
}

4.可选链?

可选链使用的是?,当对象的属性不存在时,会短路,直接返回undefined。如果存在,则继续执行。

type Person = {
	name:string
	friend?:{
		name:string
		age?:number
		girlFriend?:{
			name:string
		}
	}
}
const info:Person = {
	name:"xiaobai",
	friend:{
		name:"bob",
		girendFriend:{
			name:"lily"
		}
	}
}
console.log(
	info.friend?.name,
	info.friend?.age,
	info.friend?.girendFriend?.name
)

补充:??和!!的作用

  • !!操作符:将一个其他类型转换成boolean类型;
  • 当操作符的左侧是 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数

5.字面量类型(literal types)

type Alignment = 'left'|'right'|'center'
function changeAlign(align:Alignment){
	console.log("修改方向",align)
}
changeAlign("left")

6.字面量推理

const info = {
	url:"wwww.baidu.com",
	method:"GET"
}
function request(url:string,method:"GET" | "POST" ){
	console.log(url,method)
}
request(info.url,info.method)

对象在进行字面量推理时,info其实是一个{url:string,method:string},所以我们没办法将一个string赋值给一个字面量类型

request(info.url,info.method as "GET")

7.类型的缩小

方法:typeof,keyof,平等缩小(比如===、!==),instanceof,in

①typeof

在TS中,检查返回的值typeof是一种类型保护

type ID = number | string

function printId(id:ID){
	if(typeof id === 'string'){
		console.log(id.toUpperCase()}else{
		console.log(id)
	}
}

②keyof:遍历key

interface Person {
	name:string;
	age:number;
}
type K1 = keyof Person

③平等缩小

我们可以使用switch或者相等的一些运算符来表达相等性(比如===、!,and !=);

tyep Direction =  'LEFT' | 'RIGHT' | 'TOP' | 'BOTTOM'


function turnDirection(direction:Direction){
	switch(direction) {
		case 'LEFT':
			console.log('转向左边')
			break;
		case 'RIGHT':
			console.log('转向右边')
			break;
		case 'TOP':
			console.log('转向上边')
			break;
		case 'BOTTOM':
			console.log('转向下边')
			break;
	}
	
}

④instanceof

检查一个值是否是另一个值的实例:

function printValue(data: Date|string){
	if(data instanceof Data){
		console.log(data.toLocaleStirng())
	}else{
		console.log(date)
	}
}

⑤in

如果指定的属性值指定的对象或其原型链中,则in返回true:

type Fish = {swim:()=>void}
type Dog = {run:()=>void}
function move(animal:Fish | Dog){
	if('swim' in anmial){
		animal.swim()
	}else{
		animal.run()
	}
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值