当前位置:网站首页>[TS] as type assertion
[TS] as type assertion
2022-06-29 01:20:00 【A meteor unwilling to fall】
List of articles
Basic usage
- Types of assertions (Type Assertion) Can be used to manually specify the type of a value .
- grammar :
value as type
1. Assert a union type as one of the types
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
/* When TypeScript When it's not sure what type of variables a union type is , We can only access properties or methods common to all types of this union type */
function getName(animal: Cat | Fish) {
return animal.name;
}
/* We need to access one of the type specific properties or methods when we are not sure about the type , such as */
function isFish(animal: Cat | Fish) {
// obtain animal.swim I will make a mistake
if (typeof animal.swim === 'function') {
return true;
}
return false;
}
/* You can use type assertions at this point , take animal Asserted as Fish, So as to solve the problem of error reporting */
function isFish(animal: Cat | Fish) {
if (typeof (animal as Fish).swim === 'function') {
return true;
}
return false;
}
- Type assertions can only 「 cheating 」
TypeScriptcompiler , There is no way to avoid runtime errors
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
function swim(animal: Cat | Fish) {
// This code hides animal May be Cat The situation of , take animal The direct assertion is Fish 了
(animal as Fish).swim();
}
/* swim The arguments accepted by the function are Cat | Fish, Once the parameter passed in is Cat Variable of type , because Cat Not on swim Method , Will cause a runtime error */
const tom: Cat = {
name: 'Tom',
run() {
console.log('run') }
};
// and TypeScript The compiler trusted our assertion , Therefore, in the call swim() There were no compilation errors when
swim(tom);
/* This example will not report an error when compiling , But an error will be reported at runtime : Uncaught TypeError: animal.swim is not a function` */
2. Assert a parent class as a more specific subclass
- When there is an inheritance relationship between classes , Type assertions are also common :
class ApiError extends Error {
code: number = 0;
}
class HttpError extends Error {
statusCode: number = 200;
}
function isApiError(error: Error) {
// Because of the parent class Error There is no code attribute , Therefore, direct access to error.code Will report a mistake ,
// You need to use type assertions to get (error as ApiError).code
if (typeof (error as ApiError).code === 'number') {
return true;
}
return false;
}
- Use
instanceofNot necessarily , Although classes can passinstanceofTo judgeerrorIs it an example of it - But in some cases
ApiErrorandHttpErrorNot a real class , It's just oneTypeScriptThe interface of (interface)
interface ApiError extends Error {
code: number;
}
interface HttpError extends Error {
statusCode: number;
}
function isApiError(error: Error) {
// Will report a mistake
if (error instanceof ApiError) {
return true;
}
return false;
}
3. Assert any type as any
- When we refer to a property or method that does not exist on this type , You're going to report a mistake :
window.foo = 1;
// index.ts:1:8 - error TS2339: Property 'foo' does not exist on type 'Window & typeof globalThis'.
- But we need to
windowAdd an attribute tofoo, And keep him from making mistakes
// Now we can use it as any Temporarily window Assert as any type
(window as any).foo = 1;
4. take any Assertion is a concrete type
In daily development , We inevitably need to deal with any Variable of type , They may be due to the failure of third-party libraries to define their own types , It can also be bad code left over from history or written by others , It may also be affected by TypeScript A scenario in which a type cannot be precisely defined due to the limitations of the type system .
- such as : There is one in the code left over by history
getCacheData, Its return value isany
function getCacheData(key: string | number): any {
return key;
}
- At this time, it is better to assert the return value after calling it into an exact type
function getCacheData(key: string | number): any {
return key;
}
getCacheData('tom') as string;
Usage comparison
1. Types of assertions vs Type conversion
- Type assertions only affect TypeScript Compile time type , The type assertion statement will be deleted in the compilation result :
function toBoolean(something: any): boolean {
return something as boolean;
}
toBoolean(1);
// The return value is 1
- In the example above , take
somethingAssert asbooleanAlthough it can be compiled , But it doesn't work , The code will become :
function toBoolean(something) {
return something;
}
toBoolean(1);
// The return value is 1
- To cast a type , You need to call the method of type conversion directly :
function toBoolean(something: any): boolean {
return Boolean(something);
}
toBoolean(1);
// The return value is true
- summary : Type assertion is not a type conversion , It doesn't really affect the type of variable
2. Types of assertions vs Type declaration
- For example, restrictions
tomThe type isCat
// Use type assertion writing
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData('tom') as Cat;
tom.run();
// Use the type declaration notation
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom: Cat = getCacheData('tom');
tom.run();
- difference
interface Animal {
name: string;
}
interface Cat {
name: string;
run(): void;
}
const animal: Animal = {
name: 'tom'
};
// Use type assertion writing
let tom = animal as Cat;
/* analysis : animal Assert as Cat, Just need to satisfy Animal compatible Cat or Cat compatible Animal that will do because Animal compatible Cat, So we can put animal Assert as Cat Assign a value to tom */
// Use the type declaration notation
let tom: Cat = animal; // At this time, it will report an error
/* analysis : animal Assign a value to tom, Need to meet Cat compatible Animal Talent It's easy to understand ,Animal It can be seen as Cat Parent class of , Of course, you can't assign an instance of a parent class to a variable of type subclass */
- summary : To increase the quality of the code , We'd better give priority to type declarations , It's also better than type assertion as The grammar is more elegant
3. Types of assertions vs Generic
- Or this one :
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData('tom') as Cat;
tom.run();
- We have a third way to solve this problem , That's generics :
/* By giving getCacheData Function adds a generic <T>, We can more standardize the implementation of getCacheData Constraints on return values , This also removes... From the code any, Is the best solution . */
function getCacheData<T>(key: string): T {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData<Cat>('tom');
tom.run();
边栏推荐
- 198. house raiding
- EdrawMax思维导图,EdrawMax组织结构图
- 我想今天买股票,可以么?现在网上开户安全么?
- I want to buy stocks today, OK? Is it safe to open an account online now?
- 第七天 脚本与特效
- EasyCVR新建用户后,视频调阅页面不能点击的问题修复
- FSS object storage how to access the Intranet
- [temperature detection] thermal infrared image temperature detection system based on Matlab GUI [including Matlab source code 1920]
- SRAM和DRAM之间的异同
- 【Proteus仿真】4x4矩阵键盘中断方式扫描 +数码管显示
猜你喜欢

立创eda学习笔记:铺铜死区?孤岛?死铜?

EasyCVR集群版本替换成老数据库造成的服务崩溃是什么原因?
[Architect (Part 38)] locally install the latest version of MySQL database developed by the server

第八天 脚本与音频

Magic Quadrant of motianlun's 2021 China Database

EdrawMax思维导图,EdrawMax组织结构图

Linux7 (centos7) setting oracle11 boot auto start
UI highly adaptive modification scheme

What is the difference between the history and Western blotting

统计学习方法(2/22)感知机
随机推荐
XML and other file contents in idea cannot be highlighted, and the file becomes gray
Check the open source projects of yyds in June!
TypeScript(7)泛型
Linux7 (centos7) setting oracle11 boot auto start
Advanced installer architect authoring tool
【温度检测】基于matlab GUI热红外图像温度检测系统【含Matlab源码 1920期】
Last week, institutional encryption asset products outflow US $423million, a record high
Is it safe and reliable for qiniu school to help open a securities account? How to drive
To the interface problems we have encountered
NOIP2006-2018 提高组 初赛试题完善程序题 CSP-S 2019 2020 初赛试题完善程序题
Blazor University (34)表单 —— 获得表单状态
QT is based on RFID Management System (applicable to most RFID Management Systems)
【RRT三维路径规划】基于matlab快速扩展随机树无人机三维路径规划【含Matlab源码 1914期】
be based on. NETCORE development blog project starblog - (13) add friendship link function
Werewolf kill casual game wechat applet template source code / wechat game source code
免疫组化和免疫组学之间的区别是啥?
EasyCVR新建用户后,视频调阅页面不能点击的问题修复
TypeScript(6)函数
大厂裁员潮下,测试人员路在何方?
最新版CorelDRAW Technical Suite2022