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的更多相关文章

  1. [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 ...

  2. 在 Typescript 2.0 中使用 @types 类型定义

    在 Typescript 2.0 中使用 @type 类型定义 基于 Typescript 开发的时候,很麻烦的一个问题就是类型定义.导致在编译的时候,经常会看到一连串的找不到类型的提示.解决的方式经 ...

  3. [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 ...

  4. [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 ...

  5. [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 ...

  6. [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 ...

  7. [TypeScript] Understand lookup types in TypeScript

    Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the proper ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. js---跨域的问题

    一:跨域一般的报错情况  一般来说,如果你在开发中需要进行跨域操作(从一个非同源网站发送请求获取数据),一般而言,你在浏览器控制台看到的结果为: 二:同源策略 说到跨域就不得不提“同源策略”. 那么, ...

  2. deep-in-es6(五)

    解构 Destructuring: 解构赋值允许使用类似数组或对象字面量的语法将数组和对象的属性赋值给给中变量. 一般情况访问数组中的前三个元素: var first = arr[0]; var se ...

  3. 数据库事务及其EF中如何处理事务

    一.基础知识 1)         使用事务级别ReadUnCommited 会产生脏读现像,意味着读取到的为UnCommited(未提交)的数据.怎么理解呢?在使用该隔离级别的事务开始后.更新了数据 ...

  4. Resource Access Based on Multiple Credentials

    A collection of multiple user credentials each associated with one of multiple different users is ob ...

  5. ORA-01653 无法在表空间扩展的解决办法 -- 增加表空间大小或给表空间增加数据文件

    转自原文 ORA-01653 无法在表空间扩展的解决办法 -- 增加表空间大小或给表空间增加数据文件 当前系统的数据量越来越大的,昨天还运行正常的数据库,突然无法使用了.经过定位发现是"OR ...

  6. sqlserver 运行正則表達式,调用c# 函数、代码

    --1.新建SqlServerExt项目,编写 C# 方法生成 SqlServerExt.dll 文件 using System; using System.Data; using System.Da ...

  7. mac自己定义tree命令

    编辑文件: vim ~/.bash_profile 在文件末尾追加: alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____| ...

  8. C#解析HTML源码

    刚做了一个小任务,需要抓取其他网站的部分数据,这里就顺便介绍使用Winista.Text.HtmlParser这个类库如何解析HTML并抓取部分数据 1.获取指定网站的页面源码 string url ...

  9. HTTP浅谈

    HTTP浅谈 1···什么是HTTP? HTTP协议就是超文本传输协议(HyperText Transfer Protocol),通俗理解是浏览器和web服务器传输数据格式的协议,HTTP协议是一个应 ...

  10. C#之菜单控件、主窗体打开子窗体、GroupBox控件使用

    一.背景 一年前有学习过C#,但没有在项目中去实际做APP,重新捡起来应用到项目中.我同事本来做好一个CANOPEN设备管理的界面,由于近期搜索了别人的开发的界面,我觉得有很多东西要重新安排,以及我已 ...