[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 ...
随机推荐
- Js将类数组转化为数组
说起伪数组,大家可能会想到arguments, 这个我们函数参数的一个类数组,是类数组的代表. 1.拥有length属性,可以使用下标来访问元素,这两点和数组相同. 2.不能使用数组的方法,他们不能使 ...
- 转 C#:使用MD5对用户密码加密与解密
C#中常涉及到对用户密码的加密于解密的算法,其中使用MD5加密是最常见的的实现方式.本文总结了通用的算法并结合了自己的一点小经验,分享给大家. 一.使用16位.32位.64位MD5方法对用户名加密 1 ...
- OpenCV —— HighGUI
分为:硬件相关部分,文件部分以及图形用户接口部分 创建窗口 —— cvNamedWindow 若设置成 CV_WINDOW_AUTOSIZE 窗口大小会随着图像的载入而根据图像大小调整,用户没办法手动 ...
- 多重背包模板 51Nod 1086
有N种物品,每种物品的数量为C1,C2......Cn.从中任选若干件放在容量为W的背包里,每种物品的体积为W1,W2......Wn(Wi为整数),与之相对应的价值为P1,P2......Pn(Pi ...
- C#引用c++DLL结构体数组注意事项(数据发送与接收时)
本文转载自:http://blog.csdn.net/lhs198541/article/details/7593045 最近做的项目,需要在C# 中调用C++ 写的DLL,因为C# 默认的编码方式是 ...
- 洛谷 P1459 三值的排序 Sorting a Three-Valued Sequence
P1459 三值的排序 Sorting a Three-Valued Sequence 题目描述 排序是一种很频繁的计算任务.现在考虑最多只有三值的排序问题.一个实际的例子是,当我们给某项竞赛的优胜者 ...
- 源代码看CoordinatorLayout.Behavior原理
在上一篇博客CoordinatorLayout高级使用方法-自己定义Behavior中,我们介绍了怎样去自己定义一个CoordinatorLayout的Behavior.通过文章也能够看出Behavi ...
- js03 数组
变量的自动转换=== 等同符:不会发生类型的自动转化! == 等值符:会发生类型自动转化.自动匹配!判断相等没有equals()方法,只有2个等号3个等号. <!DOCTYPE HTML PUB ...
- Android开发经验之获取画在画布上的字符串长度、宽度(所占像素宽度)
Android中获取字符串长度.宽度(所占像素宽度) 计算出当前绘制出来的字符串有多宽,可以这么来! 方法1: Paint paint = new Paint(); Rect rect = new R ...
- startActivityForResult()的用法
举例说我想要做的一个事情是,在一个主界面(主Activity)上能连接往许多不同子功能模块(子Activity上去),当子模块的事情做完之后就回到主界面,或许还同时返回一些子模块完成的数据交给主Act ...