[TypeScript] Using Assertion to Convert Types in TypeScript
Sometimes the compiler needs help figuring out a type. In this lesson we learn how to help out the compiler with Typescript type assertion.
We have a SuperHero
and a BadGuy
. Let's make a function that saves the day if the function's argument is a SuperHero
, and a commits a bad deed if its argument is a BadGuy
. Our function needs to accept something that could be a SuperHero
or a BadGuy
.
interface SuperHero {
powers: string[];
savesTheDay: () => void;
} interface BadGuy {
badDeeds: string[];
getRandomBadDeed: () => string;
commitBadDeed: () => void;
} function saveDayOrBadDeed(something: SuperHero | BadGuy) {
if (something.powers) {}
}
The IDE is telling us something's wrong.
assertion.ts(,): error TS2339: Poperty 'powers' does not exist on type 'SuperHero | BadGuy'.
This is because the compiler is evaluating both types of the union-type argument. Since the BadGuy
doesn't have powers, something doesn't have powers. We can get a hold of the SuperHero
's power's property by asserting that something is a SuperHero
.
An assertion is how we told the compiler, "We have some information about something's type that it doesn't." There are two different syntaxes for assertion. We're using the as
type syntax, which goes behind the value. We're putting something in parens in order to isolate it from its property. If we remove the parens we can't make the assertion.
function saveDayOrBadDeed(something: SuperHero | BadGuy) {
if ((something as SuperHero).powers) {}
} //or if (<SuperHero>something.powers) {} // angle bracket syntax, doesn't work with JSX
function saveDayOrBadDeed(something: SuperHero | BadGuy) {
if ((something as SuperHero).powers) {
(something as SuperHero).savesTheDay();
} else {
(something as BadGuy).commitBadDeed();
}
} saveDayOrBadDeed(dazzler); // Dazzler transduces sonic vibrations into light to save the day!!!
saveDayOrBadDeed(badGuy); // BadGuy farts on old folks
[TypeScript] Using Assertion to Convert Types in TypeScript的更多相关文章
- [TypeScript] Using Interfaces to Describe Types in TypeScript
It’s easy to pass the wrong value to a function. Typescript interfaces are great because they catch ...
- 在 Typescript 2.0 中使用 @types 类型定义
在 Typescript 2.0 中使用 @type 类型定义 基于 Typescript 开发的时候,很麻烦的一个问题就是类型定义.导致在编译的时候,经常会看到一连串的找不到类型的提示.解决的方式经 ...
- [TypeScript] Transform Existing Types Using Mapped Types in TypeScript
Mapped types are a powerful and unique feature of TypeScript's type system. They allow you to create ...
- [TypeScript] Query Properties with keyof and Lookup Types in TypeScript
The keyof operator produces a union type of all known, public property names of a given type. You ca ...
- [TypeScript] Represent Non-Primitive Types with TypeScript’s object Type
ypeScript 2.2 introduced the object, a type that represents any non-primitive type. It can be used t ...
- [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript
TypeScript’s discriminated union types (aka tagged union types) allow you to model a finite set of a ...
- [TypeScript] Understand lookup types in TypeScript
Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the proper ...
- [TypeScript] Dynamically Allocate Function Types with Conditional Types in TypeScript
Conditional types take generics one step further and allow you to test for a specific condition, bas ...
- [TypeScript] Define Custom Type Guard Functions in TypeScript
One aspect of control flow based type analysis is that the TypeScript compiler narrows the type of a ...
随机推荐
- ASP.NET MVC Web API 学习笔记---第一个Web API程序---近来很多大型的平台都公开了Web API
1. Web API简单说明 近来很多大型的平台都公开了Web API.比如百度地图 Web API,做过地图相关的人都熟悉.公开服务这种方式可以使它易于与各种各样的设备和客户端平台集成功能,以及通过 ...
- 分享一个表格插入和删除编辑功能用jQuery实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Linear Decoders
Sparse Autoencoder Recap In the sparse autoencoder, we had 3 layers of neurons: an input layer, a hi ...
- JavaScript--数据结构与算法之二叉树
树是一种非线性的数据结构,以分层的方式存储数据. 二叉树:查找非常快,而且二叉树添加或者删除元素也非常快. 形象的可以描述为组织结构图,用来描述一个组织的结构.树是由边连接的点组成.树的一些基本概念: ...
- XML学习总结(1)——XML入门
一.XML语法学习 学习XML语法的目的就是编写XML 一个XML文件分为如下几部分内容: 文档声明 元素 属性 注释 CDATA区 .特殊字符 处理指令(processing instruction ...
- hive学习笔记-高级查询
聚合函数 count计数 count(*):不全都是NULL.就加1:count(1):当仅仅要有一列是NULL就不会加1:count(col):当col列不为空就会加1 sum求和 sum(可转成数 ...
- heap-adb shell查看堆栈使用
今天在使用eclipse中的heap查看oom的时候,发现手机(eng版本)非常的卡,后来换成usr版本,又连接不上eclipse.最后听别人说,可以使用adb shell进行查看.指令如下 adb ...
- 关于Django的登录系统
首先需要明确的是登录的本质:登录就是服务器确认当前用户的身份,并将数据库中的记录提取匹配 默认的登录系统是用户名密码方式,这种方式很平常,也没什么特别的.这里主要说的是第三方验证登录 通常第三方验证登 ...
- Scala——构造函数
Scala的构造函数分为主构造函数和辅助构造函数. 辅助构造函数 辅助构造函数比较容易理解,它们同C++和Java的构造函数十分类似,只有两处不同: 1.辅助构造函数的名称为this,这主要是考虑到在 ...
- ImageButton-设置background跟src
xml中添加ImageButton的background跟src <ImageButton android:id="@+id/tv3" android:layout_widt ...