The ko.mapping function is throwing an error because it cannot access the property 'fromJS' which is undefined

I am currently exploring typescript and attempting to integrate knockout.mapping into my project, but I'm facing some challenges.

Despite installing the necessary libraries for knockout and knockout.mapping, along with their respective "@types" declarations, I still can't seem to get it to function properly.

Within my laravel project, I am utilizing typescript and leveraging laravel mix to compile the JavaScript files.

Below is a snippet of my code:

///<reference path="../../../../node_modules/@types/jquery/index.d.ts"/>
///<reference path="../../../../node_modules/@types/knockout/index.d.ts"/>
///<reference path="../../../../node_modules/@types/knockout.mapping/index.d.ts"/>

import * as ko from "knockout";
import * as $ from "jquery";

$(function(){
    // Simple test to verify if ko.mapping exists on the ko object. Unfortunately, it does not appear to be available.
    console.log("Message from jQuery Done", (ko));
});

class MyModel {
    _data: any;
    constructor(the_data: object)
    {
        let self = this;
        let example_observable = ko.observable(); // This works fine

        ko.mapping.fromJS(the_data, self._data); // Throws an error - Cannot read property 'fromJS' of undefined
    }
}

let myModel = new MyModel({"x": "y"});
ko.applyBindings(myModel);

My package.json file lists the dependencies for knockout and knockout.mapping.

    "@types/jquery": "^3.3.6",
    "@types/knockout": "^3.4.58",
    "@types/knockout.mapping": "^2.0.33",
    "ajv": "^6.5.2",
    "knockout": "^3.4.2",
    "knockout.mapping": "^2.4.3",

I am struggling to comprehend what I might be doing incorrectly.

Any assistance would be greatly appreciated.

Thank you in advance.

Answer №1

It seems like the Knockout mapping script may not be loaded in your browser correctly. This script is separate from the core Knockout library.

If you haven't already, you can download it from here: https://www.npmjs.com/package/knockout-mapping

Make sure to include it in your page or bundle. Just referencing types does not automatically provide access to the mapping library.

To quickly check if it's working, try adding a script tag that references the mapping library from a CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>

One more thing to note - there's no need for the following line of code:

let self = this;

In TypeScript, the scoping of "this" is handled better, so you can directly refer to "this".

Answer №2

This solution worked perfectly for me. It may not be the most elegant, but it gets the job done.

I encountered an issue with "laravel mix".

To resolve this, I needed to make the following addition in my webpackconfig:

mix.webpackConfig({   
    //...
    externals: { // I assumed any "global" libraries would go here.
        'knockout': 'ko'
    }
    //...
});

In my HTML file, I had to include the following:

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>

And just like that, problem solved!

I attempted to use mix.autoload without success, perhaps due to my lack of understanding on how to properly utilize it.

If this answer seems inadequate, please let me know and I will remove the acceptance.

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

I am having trouble locating the name 'React' within the function variable when using Typescript with generic arguments

Is there a way to store a typescript function with generic arguments in a variable? function identity<T>(arg: T): T { return arg; } I attempted to do it like this but got an error message saying Cannot find name 'React' const identity = ...

Tips for defining types for specific CSS properties in TypeScript, such as variables

Perhaps there are already solutions out there, and I appreciate it if you can share a link to an existing thread. Nevertheless... In React, when I use the style prop, I receive good autocompletion and validation features like this example: What am I look ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

Discovering the data type from its textual representation

Is it possible for TypeScript to automatically determine the generic argument of assertTypeof based on the value of expectedType? I am looking for a way to use the function below without having to specify number multiple times. playable example type Typ ...

Utilize ngx-translate with an array as interpolation values

When working with ngx-translate, I use the instant method to translate messages into the user's language. These messages are provided as JSON objects and some of them contain dynamic values: { "message.key": "First value is {{0}} and se ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

What is the best way to notify the parent Observable of an inner Observable’s error or success within nested Observables?

How can the outer Observable be notified of success or error in nested Observables? Why are onNext and onCompleted undefined within the inner Observable? public updateDocument(item: Document): Observable<any> { this.firstUseOfflineContainer(); ...

What is the solution to fixing a 400 bad request error in Angular Routing?

Encountering an issue on a particular route where a 400 error is displayed in the screenshot every now and then. It seems to work fine for a few minutes after deleting cookies, but the error resurfaces after accessing it multiple times. Other routes are fu ...

The reCAPTCHA feature in Next.js form is returning an undefined window error, possibly due to an issue with

Trying to incorporate reCAPTCHA using react-hook-form along with react-hook-recaptcha is posing some challenges as an error related to 'window' being undefined keeps popping up: ReferenceError: window is not defined > 33 | const { recaptchaL ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...

What could be the reason for my dynamic image not appearing in a child component when using server-side rendering in Nuxt and Quasar

Currently, I am tackling SSR projects using Nuxt and Quasar. However, I encountered an issue when trying to display a dynamic image in a child component as the image is not being shown. The snippet of my code in question is as follows: function getUrl (im ...

Tips for utilizing parameters within SQL Server

Hello everyone! I am new to SQL Server in Azure functions using Typescript. I am currently facing an issue while trying to update a row in the database using declared variables, particularly with VARCHAR types. Strangely, it works fine in the database tool ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the ro ...

Opening a modal from a different component in Angular 6

I am attempting to launch a modal that is associated with a separate component. However, I encountered an error ERROR TypeError: Cannot read property 'show' of undefined Here is my code: product-catalog.component.html <app-cart-table-modal& ...

Unable to start an expo project in bare workflow using TypeScript

Can someone help me with setting up an expo bare workflow using TypeScript? I ran the command "expo init [project name]" in my terminal, but I can't seem to find the minimal (TypeScript) option. ? Choose a template: » - Use arrow-keys. Return to sub ...

I attempted to copy the "koa" module from my node_modules folder to a custom typeRoots directory, but it doesn

I want to use Ant Design UI, and I hope to import the script tag with the .min.js label, like this: <script src="//cdn.staticfile.org/react/15.4.1/react.min.js"></script> <script src="//cdn.staticfile.org/react/15.4.1/react-with-addons.min. ...

The element class type 'xxx' is lacking several properties compared to the 'ElementClass' type, including context, setState, forceUpdate, props, and others. This issue is flagged with error code TS2605

Encountering an error while attempting to execute my react app: D:/React/my-components/src/App.tsx TypeScript error in D:/React/my-components/src/App.tsx(23,4): JSX element type 'Confirm' is not a constructor function for JSX elements. ...

An issue occurred while attempting to differentiate the '[object Object]'. Angular-11 Application only accepts arrays and iterables for this operation

When using *ngFor, I am facing an issue with fetching data from my component.ts to my component.html Interestingly, the same method works for one class but not for another. Let's take a look at my service class: export class FoodListService { priv ...