Using the OR notation to declare the property name with 2 types is not functioning as expected for me

I'm having trouble with this solution. Here is the link to the source:

Is it possible to declare a property with multiple types using the OR notation like this?

export interface OnboardingSchoolModel {

    level?: string | number;
    school?: string;

}

I attempted this approach but it doesn't seem to be working. Any suggestions on how to work around this issue?

I prefer to restrict the types for the property rather than using any.

Encountering a compile-time error:

(property) OnboardingSchoolModel.level?: string | number
Argument of type 'string | number' is not assignable to parameter of type 'string'.
  Type 'number' is not assignable to type 'string'.

Example of Usage:

  getSchools(): Promise<OnboardingSchoolModel[]> {
return new Promise(resolve => {
  this.onboardingService.getSchools().pipe(first()).subscribe((schools: any) => {
    const schoolList: OnboardingSchoolModel[] = [];
    forEach(schools, (s: any) => {
      const schoolDocumentData: OnboardingSchoolModel = s.payload.doc.data();
      const id: string = s.payload.doc.id;
      const school: OnboardingSchoolModel = {

        level: this.getIndexForLevel(schoolDocumentData.level),

      };
      schoolList.push(school);
    });
    resolve(schoolList);
  }, err => console.log(err));
});

}

getIndexForLevel(levelString: string): number {
    let levelIndex: number;
    switch (levelString) {
      case LevelEnum.High_School:
        levelIndex = 0;
        break;
      case LevelEnum.College:
        levelIndex = 1;
        break;
      case LevelEnum.Graduate:
        levelIndex = 2;
        break;
      default:
    }
    return levelIndex;
  }

Answer №1

Feedback from the Original Poster

This method is working perfectly for me. Specifically, the

getIndexForLevel(levelString: string | number)
function.

  getIndexForLevel(levelString: string | number): number {
    let levelIndex: number;
    switch (levelString) {
      case LevelEnum.High_School:
        levelIndex = 0;
        break;
      case LevelEnum.College:
        levelIndex = 1;
        break;
      case LevelEnum.Graduate:
        levelIndex = 2;
        break;
      default:
    }
    return levelIndex;
  }

Original Response:

Your function getIndexForLevel() requires a string argument, so make sure to always provide a string value.

level: this.getIndexForLevel(schoolDocumentData.level as string),

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

Embrace AngularJS: Employ the ".then" method and retrieve the response

In order to send a http request and receive the response of this request, I am trying to implement a mechanism where if the data is successfully saved, I can retrieve database information, and if it fails to save, I can track errors. To achieve this, I pla ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...

Completing a fetch promise and sending the outcome to a function that is not awaited

I have a function that retrieves data from a Postgresql database and returns it. The expected behavior is to fetch the data using the async function getCat(), process it in const Catalogue, and then return it to a ReactJS component. catalogue.tsx: import ...

The binding on an AngularJS page is only retained by the final directive applied

Having a few directives that need to be reused as elements, I've decided to implement scope isolation. Each directive is associated with its own controller, which retrieves data from MongoDB based on the URL. The issue I'm facing is that only th ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

The light slider feature is experiencing technical difficulties within the Bootstrap model

I am experiencing an issue with the Light Slider in a Bootstrap modal. Strangely, when I press F12 for inspect element, the Light Slider starts working. For more details and to see the link provided in the comment below, can anyone offer assistance, plea ...

Fixing prop passing issues in Vue.js components to prevent errors

My Vue-cli install with TypeScript is set up to render JSX using a boilerplate. However, I am facing an issue when trying to pass a property to the HelloWorld component. Here's what my code looks like: export default Vue.extend({ name: 'App&apo ...

Handling Errors in Node.js with Express

To access the complete repository for this project, visit: https://github.com/austindickey/FriendFinder After downloading the directory, follow the instructions in the ReadMe to set it up on your computer. Encountering an issue where my survey.html page ...

What causes the behavior of Node.js to be the way it is?

Check out this code snippet function removePrototype() { var obj = {}; for (var _i = 0, _a = Object.getOwnPropertyNames(obj.__proto__); _i < _a.length; _i++) { var prop = _a[_i]; obj[prop] = undefined; } obj.__proto__ = ...

Having difficulty replicating the same effect across all five canvas elements

After following the code provided by j08691 here for canvas, everything worked flawlessly. However, I encountered an error in JavaScript when trying to implement it on multiple canvas elements. As a beginner in JavaScript, I would greatly appreciate any as ...

Attempting to minimize the number of jQuery calls within a Domino XPage

Trying to incorporate the 'DataTables' table plug-in for jQuery into a basic Domino XPage. Successfully loaded required libraries from CDN sources... JQuery: ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js DataTables: cdn.datatables. ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Having trouble invoking html2canvas within an AngularJS app

When I define html2canvas functions in my controller, the alert in html2canvas doesn't get fired and my canvasToImageSuccess function is not executed. Am I missing something here? In my controller, I have defined html2canvas functions as shown below ...

Retrieving raw PCM data from webAudio / mozAudio APIs

I have been exploring ways to store the output from the webAudio API for future reference. It seems that capturing PCM data and saving it as a file might meet my needs. I am curious to know if the webAudio or mozAudio APIs have built-in functionality for ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

What is the method to transfer a declared object from a .ejs file to my index.js file?

I have a simple script embedded in my .ejs file. The script captures input data from the user and stores it in an object. Now, my goal is to send this object to my index.js file, where I plan to utilize the data with a node module called coap (similar to ...

Alignment of Bootstrap thumbnails in a horizontal layout

After adding the thumbnail class to my thumbnails div, I noticed that some of the thumbnails were smaller in size than others. Wanting them all to have the same height, I decided to give each thumbnail a fixed height of 210px. However, this caused the sm ...

Next.js Refresh Screen

Is there a way to refresh my client's web page from the server at a specific time? I need the client's page to be refreshed at 12pm, and although I'm using a scheduler, it doesn't seem to be automatically refreshing the web page on the ...

Authenticating Users with Laravel and Vue.js

In my Vue.js application, I have implemented a login system. The main script in my main.js file includes the necessary imports and configurations: import Vue from 'vue'; import NProgress from 'nprogress'; import Resource from 'vue ...

What is the process for generating an object type that encompasses all the keys from an array type?

In my coding journey, I am exploring the creation of a versatile class that can define and handle CRUD operations for various resources. The ultimate goal is to have a single generic class instance that can be utilized to generate services, reducer slices, ...