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. BZOJ 1572 贪心(priority_queue)

    思路: 维护两个堆 一个按时间 (从后到前)的 另一个是按价值(从大到小)的 从时间的堆向价值的堆倒 每回(合法状态下)取当前的堆顶 判一判 //By SiriusRen #include <q ...

  2. Elasticsearch之shield(权限)插件安装之后的浏览详解

    前期博客 Elasticsearch-2.4.3的3节点安装(多种方式图文详解)(含 head.kopf.marvel.shield和watcher插件安装和使用) 访问es:-u es_admin ...

  3. C语言-常量指针与指针常量

    最近倪健问我一个问题,他说:什么是常指针?什么是指向常变量的指针?请举例说明 我查阅资料后这么回答他了, 指针常量(常指针):int * const p : 指针是一个常量,也就是说它始终指向那个地址 ...

  4. python 补0的方法

    # 方法一 z = 'bb' z.zfill(6) ----'0000bb' n = ' n.zfill(5) ----' # 方法二 ' " ---- '报错' # 方法的区别 方法二只能 ...

  5. 使用MERGE语句同步表

    先建好測试环境: USE TEMPDB GO IF OBJECT_ID('T1') IS NOT NULL DROP TABLE T1 IF OBJECT_ID('T2') IS NOT NULL D ...

  6. shiro session管理

    http://shiro.apache.org/session-management.html Using Sessions The SessionManager Session Timeout Pe ...

  7. java 三次样条插值 画光滑曲线 例子

    java 三次样条插值 画光滑曲线 例子 主要是做数值拟合,根据sin函数采点,取得数据后在java中插值并在swing中画出曲线,下面为截图  不光滑和光滑曲线前后对比:    代码: 执行类: p ...

  8. Appium定义接口测试

    1.Appium如何执行 Appium作为一个服务器,python的脚本代码交给Appium服务器,Appium再去与设备交互. desired_cap = {} desired_cap['platf ...

  9. Shiro学习总结(4)——Shrio登陆验证实例详细解读

    最终效果如下: 工程整体的目录如下: Java代码如下: 配置文件如下: 页面资源如下: 好了,下面来简单说下过程吧! 准备工作: 先建表: [sql] view plain copy drop ta ...

  10. 洛谷——P1816 忠诚

    https://www.luogu.org/problem/show?pid=1816#sub 题目描述 老管家是一个聪明能干的人.他为财主工作了整整10年,财主为了让自已账目更加清楚.要求管家每天记 ...