Is there a way to achieve this using a fresh and sleek typescript assertion function?

Presented below is the snippet of code:

type Bot = BotActive | BotInactive;

class BotActive {
    public readonly status = "active";

    public interact() {
        console.log("Hello there!");
    }
}

class BotInactive {
    public readonly status = "inactive";
}

function canInteract(bot: Bot) {
    if (bot.status === "inactive") throw Error("Bot cannot interact when it's inactive!");

    bot.interact();
}

Now, I am interested in verifying the status of the bot using a TypeScript assertion function! Here's what I have in mind:

function canInteract(bot: Bot) {
    assertBotStatus(bot, "active");

    bot.interact();
}

Is there a way to achieve this? If so, how would the assertBotStatus function be implemented?

Your help is greatly appreciated!

Answer №1

One way to validate the type of an argument is by using assertion statements -

asserts <<arg>> is <<type>>
.

function assertRobotStateOn(robot: Robot): asserts robot is RobotOn {
  if (robot.state !== 'on') {
    throw new Error('Robot is Off!');
  }
}
function assertRobotStateOff(robot: Robot): asserts robot is RobotOff {
   if (robot.state !== 'off') {
    throw new Error('Robot is On!');
  }
}
function maybeSpeak(robot: Robot) {
    assertRobotStateOn(robot);

    robot.speak();
}
maybeSpeak(new RobotOff());

For more information, you can refer to:

Answer №2

Success! I've discovered a solution using overloaded assertion functions! Check out the code snippet below:

type Android = Active | Inactive;

class Active {
    public readonly status = "active";

    public greet() {
        console.log("Hello there!");
    }
}

class Inactive {
    public readonly status = "inactive"
}

function maybeGreet(android: Android) {
    assertAndroidStatus(android, "active");

    android.greet();
}

function assertAndroidStatus(robot: Android, status: "active"): asserts robot is Active;
function assertAndroidStatus(robot: Android, status: "inactive"): asserts robot is Inactive;
function assertAndroidStatus(robot: Android, state: "active" | "inactive") {
    if (robot.status !== state) throw new Error("Error: Invalid status");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue while trying to integrate custom commands using the addCommand function in WebDriverIO

When using the addCommand function to add a new command, I encountered an error message that states: [ts] Property 'WaitForElementsAmount' does not exist on type 'Client<void>'. Here is an example of the code snippet I used: br ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

Execute the CountUp function when the element becomes visible

Currently, I am implementing the following library: https://github.com/inorganik/ngx-countUp Is there a way to activate the counting animation only when the section of numbers is reached? In other words, can the count be triggered (<h1 [countUp]="345 ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

The initial invocation of OidcSecurityService.getAccessToken() returns null as the token

Our internal application requires all users to be authenticated and authorized, including for the home page. To achieve this, we use an HttpInterceptor to add a bearer token to our API requests. Initially, when rendering the first set of data with the fir ...

Is there intellisense support for Angular 2 templates in Visual Studio?

Is it possible for Visual Studio to provide autocomplete suggestions for properties of a Typescript component within a separate HTML view template? ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Issues with the execution of Typescript decorator method

Currently, I'm enrolled in the Mosh TypeScript course and came across a problem while working on the code. I noticed that the code worked perfectly in Mosh's video tutorial but when I tried it on my own PC and in an online playground, it didn&apo ...

How can I dynamically replace a specific element inside a .map() function with a custom component when the state updates, without replacing all elements at once?

I'm currently developing a task management application and I need to enhance the user experience by implementing a feature that allows users to update specific tasks. When a user clicks on the update button for a particular task, it should replace tha ...

fill the designated column in accordance with the specific criteria

Is there a method to automatically fill in a specific column based on certain conditions? I am looking to populate the column labeled [Last] when the column index is 1 and the corresponding name is [First]. import {Component, OnInit} from '@angular ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

amChartv5 on Angular is successfully displaying a Gantt chart that includes multiple categories with the same name being resolved

I've been working on integrating an amCharts v5 gantt chart with Angular 13. Each bar in the chart represents a project, and if there are multiple occurrences of a category, they should stack like a timeline. I've successfully retrieved data from ...

Swiping in Angular2 gets a new twist with Swiper typings

Having trouble importing typings for Swiper into my Angular 2 project. After installing Swiper and its typings using npm, I tried including Swiper in my component like this: import { Swiper } from 'swiper'; However, Atom displays an error: ...

Playing around with TypeScript + lambda expressions + lambda tiers (AWS)

Having trouble importing modules for jest tests in a setup involving lambdas, lambda layers, and tests. Here is the file structure: backend/ ├─ jest.config.js ├─ package.json ├─ babel.config.js ├─ layers/ │ ├─ tsconfig.json │ ├ ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...