TS中断言、转换的应用

1.TS 类型断言定义

把两种能有重叠关系的数据类型进行相互转换的一种 TS 语法,把其中的一种数据类型转换成另外一种数据类型。类型断言和类型转换产生的效果一样,但语法格式不同。

2.TS 类型断言语法格式

A 数据类型的变量 as B 数据类型 。

A 数据类型和 B 数据类型必须具有重叠关系。

3.TS 类型断言使用规则和场景
(1)如果 A,B 如果是类并且有继承关系

【 extends 关系】无论 A,B 谁是父类或子类, A 的对象变量可以断言成 B 类型,B 的对象变量可以断言成A类型 。但注意一般在绝大多数场景下都是把父类的对象变量断言成子类。

class People {public myusername!: string;public myage!: number;public address!: stringpublic phone!: stringconstructor() {}eat() {}step() {console.log("People=>step");}
}class Stu extends People {public username!: stringpublic age!: number;public address!: stringconstructor(username: string, age: number, address: string, public phone: string) {super();this.address = address;}study() {}
}let people = new People()//let result = people as Stu;// 类型断言 正确
let result = <Stu>people;// 类型转换 正确
result.study();let stu = new Stu("wangwu", 23, "北京", "123")
let result2 = stu as People;// 正确
(2)如果 A,B 如果是类,但没有继承关系

两个类中的任意一个类的所有的 public 实例属性【不包括静态属性】加上所有的 public 实例方法和另一个类的所有 public 实例属性加上所有的 public 实例方法完全相同或是另外一个类的子集,则这两个类可以相互断言,否则这两个类就不能相互断言。

// 类型断言中的不能相互重叠问题:
//   两个类之间断言的规则:
//   两个类中任意一个的属性和方法是另一个类的属性和方法完全相同或子集,则这两个类可以相互断言
//   否则这两个类就不能相互断言class People {constructor(public username: string, public age: number,public address: string) {}
}class Stu {public username!: stringpublic age!: number;public address!: stringpublic phone!:string;constructor(username: string, age: number, address: string) {this.address = address;}
}let people = new People("wangwu", 23, "beijing")
let stuedConvert = people as Stu;
let stu = new Stu("wangwu", 23, "北京")
let peopledConvert = stu as People;
(3)如果 A 是类,B 是接口,并且 A 类实现了 B 接口【implements】,则A 的对象变量可以断言成 B 接口类型,同样 B 接口类型的对象变量也可以断言成A类型 。
interface People {username: string, age: number, address: string, phone: string
}class Stu implements People {public username!: stringpublic age!: number;public address!: stringpublic phone!: stringpublic kk() {}constructor(username: string, age: number, address: string) {this.address = address;}
}let people: People = { username: "wangwu", age: 23, address: "11", phone: "111" }
let result = people as Stu;//正确
let result2 = <Stu>people;// 类型转换 正确let stu = new Stu("wangwu", 23, "北京")
stu as People;// 正确
(4)如果 A 是类,B 是接口,并且 A 类没有实现了 B 接口,则断言关系和第2项的规则完全相同。
interface People {username: string, age: number, address: string, phone: string
}class Stu {public username!: stringpublic age!: number;public address!: stringpublic phone!: stringpublic kk() {}constructor(username: string, age: number, address: string) {this.address = address;}
}let people: People = { username: "wangwu", age: 23, address: "11", phone: "111" }
let result = people as Stu;//正确let stu = new Stu("wangwu", 23, "北京")
stu as People;// 正确
(5)如果 A 是类,B 是 type 定义的数据类型

type 定义的数据类型是引用数据类型,例如 Array, 对象,不能是基本数据类型,例如 string,number,boolean,并且有 A 类实现了 B type 定义的数据类型【 implements】,则 A 的对象变量可以断言成 B type 定义的对象数据类型,同样 B type 定义的对象数据类型的对象变量也可以断言成 A 类型 。

type People = {username: string, age: number, address: string, phone: string
}class Stu implements People {public username!: stringpublic age!: number;public address!: stringpublic phone!: stringconstructor(username: string, age: number, address: string) {this.address = address;}
}let people: People = { username: "wangwu", age: 23, address: "11", phone: "111" }
let result = people as Stu;//正确let stu = new Stu("wangwu", 23, "北京")
stu as People;// 正确
(6)如果 A 是类,B 是 type 定义的数据类型,并且 A 类没有实现 B type定义的数据类型,则断言关系和第2项的规则完全相同。
type People = {username: string, age: number, address: string, phone: string
}
class Stu {public username!: stringpublic age!: number;public address!: stringconstructor(username: string, age: number, address: string) {this.address = address;}
}let people: People = { username: "wangwu", age: 23, address: "11", phone: "111" }
let result = people as Stu;//正确let stu = new Stu("wangwu", 23, "北京")
stu as People;// 正确
(7)如果 A 是一个函数上参数变量的联合类型,例如 string |number,那么在函数内部可以断言成 string 或number 类型。
function selfMutiply(one: string | number) {one as number +3;
}
(8)多个类组成的联合类型断言

例如:let vechile: Car | Bus | Trunck。 vechile 可以断言成其中任意一种数据类型。 例如 vechile as Car, vechile as Bus , vechile as Trunck 。

class Vechile {static count: number = 3;public brand: string;public vechileNo: string;public days: number;public total: number = 0;public deposit: number;constructor(brand_: string, vechileNo_: string, days_: number, deposit_: number) {this.brand = brand_;this.vechileNo = vechileNo_;this.days = days_;this.deposit = deposit_;}public calculateRent() {}payDesposit() {}public safeShow() {}
}class Car extends Vechile {public type: string;constructor(brand_: string, vechileNo_: string, days_: number,deposit_: number, type_: string) {super(brand_, vechileNo_, days_, deposit_);this.type = type_;}public getPriceByType() {}public calculateRent() {}public checkIsWeigui(isOverWeight: boolean) {}
}class Bus extends Vechile {public seatNum: numberconstructor(brand_: string, vechileNo_: string, days_: number,deposit_: number, seatNum_: number) {super(brand_, vechileNo_, days_, deposit_);this.seatNum = seatNum_;}public getPriceBySeatNum() {}public checkIsOverNum(isOverWeight: boolean) {}
}class Truck extends Vechile {ton!: numberconstructor(brand_: string, type_: string,days_: number, deposit_: number, ton_: number) {super(brand_, type_, days_, deposit_);this.ton = ton_;}checkIsOverWeight(isOverWeight: boolean) {}CalRentPrice() {}public calRent() {}public calDesposit() {}
}class Customer {rentVechile(vechile:Bus | Truck | Car) {// 下面进行断言、转换//<Bus>vechile <==等同==> vechile as Bus//vechile as unknown//vechile.calculateRent()//(vechile as Bus).checkIsOverNum(false)}
}
(9)任何数据类型都可以转换成 any 或 unknown 类型**,any 或 unknown 类型也可以转换成任何其他数据类型。
function add(one: string | number, two: string | number) {return one as any + two as any
}console.log(add(3, 5))
console.log(add("3", 5))
4.类型断言存在的意义和应用场景:

场景1:顾客在执行汽车租赁项目租赁价格计算方法中调用每一个类的独有方法时使用

场景2:对象中的 Symbol 数据类型取值问题

场景3:加法计算,巧用 as any。

let symid = Symbol("objid")
let obj = { [symid]: 101, username: "wangwu", age: 23 }
let username = obj["username"]
//let objid=obj[symid]//类型“symbol”不能作为索引类型使用
// 解决:
let objid = obj[symid as any]
//let objid2 = obj[symid as unknown]//类型“unknown”不能作为索引类型使用
//let symidunknown = symid as unknown// 可以转换成unknown,正确

脚踏实地行,海阔天空飞

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/219920.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Clickhouse】float 计算误差

Float 为二进制 精度有损&#xff0c;每次求和的结果可能一样&#xff0c;由于相加顺序不一样导致。 bigDecimal是无损的&#xff0c;底层为十进制&#xff0c;但是存储占用更大。 举例&#xff1a; SELECT 0.1 0.2 AS result 在 ClickHouse 中&#xff0c;运行上述查询&am…

尚硅谷JavaWeb电子书城项目(Java+Mysql+Tomcat+Jsp)

自己写的在线电子书城项目&#xff0c;可改写&#xff0c;添加功能&#xff0c;如打折&#xff0c;分类&#xff0c;用户管理&#xff0c;评论等功能。 使用方法&#xff1a; 1.使用idea导入项目。 2.数据库要用项目resource文件里的book.sql文件建立。 3.修改jdbc.properi…

C++ 重载括号运算符示例

重载括号运算符的写法是&#xff0c; 返回值 operator() ( 表达式表 ) 参数个数不限&#xff1b; VC6新建一个单文档工程&#xff1b; 添加一个示例类&#xff0c;比较短&#xff0c;直接加到视类h文件的头部&#xff1b; class A { public:// 重载 括号 () 运算符int oper…

理解 Proxy 和 Object.defineProperty:提升你的 JavaScript 技能(下)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

IDEA利用插件完成properties与yml的互相转换(mac与wins通用)

步骤一、插件安装 点击屏幕左上方的IDEA&#xff0c;然后点击Preferences(相当于wins里的settings) 进入后点击Plugins&#xff0c;在插件商城中搜索并安装 Convert YAML and Properties File 这个插件 二、使用 右键选择你需要转换的配置文件&#xff0c;选择Convert YAML …

HarmonyOS给应用添加视频播放功能

Video组件的使用 概述 在手机、平板或是智慧屏这些终端设备上&#xff0c;媒体功能可以算作是我们最常用的场景之一。无论是实现音频的播放、录制、采集&#xff0c;还是视频的播放、切换、循环&#xff0c;亦或是相机的预览、拍照等功能&#xff0c;媒体组件都是必不可少的。…

JAVA高级(后端需深入移步)

单元测试&#xff1a;使用Junit单元测试框架 使用Junit单元测试&#xff1a; 通过左侧的对❌来进行提示 Junit框架的常见注解&#xff1a; 反射&#xff08;用于框架&#xff0c;也是最重要&#xff09;&#xff1a;展示框架的成员信息 由于是用于对象&#xff0c;即使在获取…

CDN是如何实现网络加速的?

最近很多网站用户都在谈论香港服务器的同时&#xff0c;也在讨论CDN加速服务的相关话题&#xff0c;谈论的目的就是想通过相关的设置和服 务来有一个好的上网体验&#xff0c;同时减少同行DDOS的攻击。 那么&#xff0c;对网站进行CDN加速服务到底能够让网络实现哪些功能呢&am…

低代码开发:数字化“装配线”的崛起

一、什么是低代码 首先,我们不妨从低代码开发的定义和起源说起。低代码开发(Low Code Development),指通过可视化的图形界面来进行应用程序开发和部署的方式,大大降低了开发门槛,用户不需要掌握传统文本编程语言就可以进行开发。 低代码开发起源于20世纪90年代,经历了3个发展…

力扣300. 最长递增子序列

动态规划 思路&#xff1a; 假设 dp[i] 为前 i 个元素构成的最长递增子序列的个数&#xff0c;包含 nums[i]&#xff1b;则 dp[i] 构成序列上一个元素 nums[j] 构成最长递增子序列 dp[j]&#xff0c;则 dp[i] dp[j] 1&#xff1b;如果动态取 j ∈ [0, i - 1]&#xff0c;则选…

Github入门

简介 github是一个基于git的代码仓库&#xff0c;可以通过git来上传和下载代码。国内类似的有gitee。 开源项目一般会申明开源协议。我们可以基于可商用的代码开发我们自己的项目&#xff0c;以期进行快速开发。 一般情况下gitee上的项目基本都够我们使用了。 git基础 Git…

二叉树(接口函数的实现)

今天继续来分享的是二叉树&#xff0c;我们废话不多说&#xff0c;直接来看下面的几个接口函数&#xff0c;然后我们把他们实现&#xff0c;我们就掌握二叉树的二分之一&#xff08;今天粉丝破千了&#xff0c;属实有点高兴了&#xff09;。 typedef char BTDataType;typedef s…

OSG加载地形

这是网上下的一个代码; 先看一下代码; KeyboardHandler.h; #ifndef KEYBOARD_HANDLER_H #define KEYBOARD_HANDLER_H #include <iostream> #include <osgGA/GUIEventHandler>class keyboardEventHandler : public osgGA::GUIEventHandler { public:typedef v…

HTML插入视频和音频(详解)

&#x1f4cd;文章目录&#x1f4cd; &#x1f9c0;一&#xff0c;简介&#x1f9c0;二&#xff0c;视频(video)&#x1f367;1&#xff0c;普通的视频插入&#x1f367;2&#xff0c;在html5中嵌入视频网站视频 &#x1f9c0;三&#xff0c;音频(audio) &#x1f9c0;一&#…

linux中的od命令与hexdump命令

初步解读两个命令 在Linux中&#xff0c;"od"和"hexdump"命令都用于以十六进制和其他格式显示文件的内容。它们提供了对文件进行二进制查看和分析的功能。以下是它们的简要说明&#xff1a; od命令&#xff1a; “od”&#xff08;octal dump&#xff09;…

德语 Alt 代码表

德语的 Alt 代码表&#xff0c;请参考下图。 输入方法就是按住 Alt 键不松开&#xff0c;然后在小键盘上输入字符&#xff0c;松开 Alt 键&#xff0c;计算机就能输出上面的字符了。 德语 Alt 代码表 - 系统容器 - iSharkFly德语的 Alt 代码表&#xff0c;请参考下图。 输入方…

Spring Security(一)架构概览

一、 Spring Security 架构概览 1. Spring Security 简介 在Java企业级开发中&#xff0c;安全管理方面的框架非常少&#xff0c;一般来说&#xff0c;主要是三种方案&#xff1a; ShiroSpring Security开发者自己实现 Spring Security基于Spring框架&#xff0c;提供了一套…

Java常用注解

文章目录 第一章、Java注解与元数据1.1&#xff09;元数据与注解概念介绍1.2&#xff09;Java注解的作用和使用1.3&#xff09;注解的分类 第二章、Mybatis框架常用注解2.1&#xff09;Mybatis注解概览2.2&#xff09;常用注解MapperScanMapperSelectInsertUpdateDeleteParam结…

学习openAI 短长期AGI计划、使命、宪章、开创性研究、产品、工作待遇等

网站的设计&#xff1a;简洁而现代 主页 使命&#xff1a;Creating safe AGI that benefits all of humanity. &#xff08;比人类更聪明的人工智能系统&#xff09;&#xff08;自己实现或帮别人实现都认为是达成使命&#xff09;&#xff08;造福全人类&#xff1a;最大限…

springboot笔记

1、springboot中的缓存标签Cacheable使用场景 Cacheable 只是为了让你省略掉是使用集合来保存缓存数据的代码&#xff0c;给你的业务代码横切入缓存的逻辑.然后使用缓存的场景就是读多写少的场景&#xff0c;读操作特别频繁的话&#xff0c;还是把热点数据缓存起来&#xff0c…