[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(24,19): 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
时间: 2024-10-09 01:07:30

[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 errors at compile time or in an IDE. In this lesson we’ll learn how to describe a type shape with Typescript interfaces. Using interface to describe a

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

在 Typescript 2.0 中使用 @type 类型定义 基于 Typescript 开发的时候,很麻烦的一个问题就是类型定义.导致在编译的时候,经常会看到一连串的找不到类型的提示.解决的方式经过了许多的变化,从 DefinitelyTyped 到 typings.最后是 @types.在 Typescript 2.0 之后,推荐使用 @types 方式. DefinitelyTyped 这个工具已经不被推荐,仅作介绍. 多数来自 javascript 的库是没有 TypeScript 类

[TypeScript] Understand lookup types in TypeScript

Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the property keys of an object. We'll use the function spyOn from Jest to illustrate how lookup types can type-safe function parameters. Considering this code:

[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 can use it together with lookup types (aka indexed access types) to statically model dynamic property access in the type system. interface Todo { id: nu

[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 to more accurately type methods such as Object.create. Don't confuse it with the Object type or {}, the empty object type, though! Type 'Object' gives

[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 variable within a type guard. This lesson explores how you can define functions and type predicates to create your own type guards similar to the Arr

[TypeScript] Catch unsafe use of &quot;this&quot; in TypeScript functions

this is probably the most tricky thing to use in JavaScript and therefore TypeScript. Fortunately there is a TypeScript compiler flag noImplicit this that can help catch unsafe usages so beginners don't get caught off guard. // tsconfig.json { "compi

[TypeScript] Sharing Class Behavior with Inheritance in TypeScript

Typescript classes make inheritance much easier to write and understand. In this lesson we look into how to set up inheritance with Typescript classes, extends and super. class ComicBookCharacter ( constructor{ public alias: string, public health: nu

[TypeScript] Union Types and Type Aliases in TypeScript

Sometimes we want our function arguments to be able to accept more than 1 type; e.g. a string or an array. This lesson will show us how to assign more than 1 type to a variable with Typescript union types and type aliases. type types = string | boole