Typescript+vue实战

一、基础类型

1.布尔值

const hasData: boolean = false;

2.字符串

const name: string = 'ysj'; 

3.数字

const age: number = 22;

4.数组

const arr1: Array<number> = [1, 2, 3, 4];

interface ArrList {
   name!: string;
   age?: number;
}

const arr2: ArrList[] = [{name: 'ysj', age: 23}, {name: 'lh'}];

// (1)在元素类型后面加上[] 
// (2)使用数组泛型Array<元素类型>

5.枚举

enum ObjType {
    name: string;
    age: number;
    isMarry?: boolean;
} 

const person1 = {name: 'ysj', age: 22, isMarry: false};
const person2 = {name: 'lh', age: 23};

6.any

当不确定变量是什么类型的时候使用

7.void

当一个函数没有返回值时使用

handelClick(): void {
   console.log('点击了');
}

8.Null和Undifined(作用不大)

const u: undefined = undefined;
const n: null = null;

9.Never

表示永不存在值的类型,例如抛出异常的时候

error(msg: string): never {
    throw new Error(message);
}

 二、Typescript新特性

1.可选链式操作符(Optional Chaining) v3.7可用

// 数据:
const userInfo = {
    name: 'ysj',
    age: 22,
    authList: ['user-manager', 'user-delete'] // 用户权限
};
// 需求:如果该用户没有权限时,显示无数据

// html

<div v-if="hasAuth">
    <span v-for="item in userInfo.authList" :key="item">{{item}}</span>
<div>
<div v-else>无权限干任何事儿呀</div>

// js
// 普通写法
get hasAuth(): boolean {
    return this.userInfo && this.userInfo.authList && this.userInfo.authList.length;
};

// 可选链式
get hasAuth(): boolean {
    return this.userInfo?.authList?.length
};

2.双问号操作符(Nullish Coalescing) v3.7可用

const a = false;
const res = a || 'foo'; // res = 'foo' 错误
// 当a等于0或flase时,也会给res赋值为foo,这时候好像不太符合要求。这时可以使用双问号操作符,只有a为null或undefined时才会被赋予默认值

const a = false;
const res = a ?? 'foo'; // res = false; 正确

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值