Console.log() show the correct object values in collapsed version but not in expanded version [duplicate]

I’m querying a third party API (ESPN Fantasy) from my front end to clean the data and use it in my app. While adding new data details, I have an issue : when trying to apply detailed raters to my players, I end up getting wrong values. So I logged the data during the process and I get this weird result :

enter image description here

The first object is the raw data from the third party API, with the correct values. The second object is what I get when I parse them. As you can see, the collapsed version of my object has the correct values but the expanded version has wrong values. Those wrong values are the one I end up with in my app.

Here is the code where I parse the data :

const basePlayerRaters: PlayerCategoriesRaters = {
  [StatsCategories.FG]: 0,
  [StatsCategories.FT]: 0,
  [StatsCategories["3PM"]]: 0,
  [StatsCategories.REB]: 0,
  [StatsCategories.AST]: 0,
  [StatsCategories.STL]: 0,
  [StatsCategories.BLK]: 0,
  [StatsCategories.TO]: 0,
  [StatsCategories.PTS]: 0,
};

const buildPlayerRaters = (
  rawRater: PlayerRatings | undefined
): PlayerCategoriesRaters => {
  const output = basePlayerRaters;
  if (rawRater) {
    rawRater.statRankings.forEach((value) => {
      const key = RaterCategories.get(value.forStat);
      if (key) {
        output[key] = value.rating;
      }
    });
  }
  console.log("build raters 2 : ", rawRater, output);

  return output;
};

I don’t understand where these wrong values come from, why I get them and, out of curiosity, why the console.log has both the good and bad data.

React class & functional components [closed]

What is the main difference between class & function Components.what is the main functionality of both component.why everyone use function components ?

Suppose i am making a applictaion those have 2 or 3 compontes .May i use different-different components in every components.

How to prevent Javascript super constructor calling a method overridden by a derived class?

I’m new to JS and implementing a polymorphic class hierachy. It appears that within the super constructor (when called from a derived constructor), ‘this’ refers to the derived class, not the super class.

So, when the super constructor calls a method that the derived class has overridden, it calls the derived class version not the (original) super class version. This is not the behaviour I wanted, as it means the super constructor behaves differently for the same input parameters when it is called via the derived constructor.

A minimum working example is below:

class A {
  constructor(x) {
    console.log("A constructor");
    this.x = x;
    this.foobar();
  }

  foobar() {
    console.log("A foobar");
  }
}

class B extends A {
  constructor(x, y) {
    console.log("B constructor");
    super(x);
    this.y = y;
  }

  foobar() {
    console.log("B foobar");
  }
}

let a = new A(123);
let b = new B(123, 456);

console.log output is:

A constructor

A foobar

B constructor

A constructor

B foobar   (I would have expected this to be 'A foobar')

Have I done something wrong, and if not is there a fairly straightforward way to ensure the original (super) method is always called by the super constructor?

Many thanks in advance for any advice.

PS: I have found similar question here:
How can I prevent calling a super function from the derived class function?

The answer given is to get the super constructor to check whether the instance is of the derived type and change behaviour accordingly. This seems cumbersome, but I could go with that if no-one can suggest a better solution.

Webpack not generating chunks for React.lazy imports with babel & react native web

I’m working on a React native web project (with custom Webpack config) and using React.lazy with dynamic imports for code splitting. However, Webpack isn’t generating separate chunks for these imports as expected. I’ve tried several solutions, but none have resolved the issue.

Code:

const Apple = React.lazy(() => import(/* webpackChunkName: "Apple" */ './Apple'));

Webpack config:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

const config = (_, argv) => ({
    target: 'web',
    entry: {
        main: path.resolve(__dirname, 'src', 'main'),
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[contenthash].js',
        chunkFilename: '[name].[contenthash].js',
    },
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        alias: {
            'react-native$': 'react-native-web',
        },
    },
    module: {
        rules: [
            {
                test: /.(tsx|jsx|ts|js)?$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true,
                        presets: [
                            ['@babel/preset-env', { modules: false }], // Transpile modern JS
                            '@babel/preset-react', // JSX support
                            'module:metro-react-native-babel-preset',
                        ],
                        plugins: [
                            'react-native-web',
                            '@babel/plugin-syntax-dynamic-import',
                            '@babel/plugin-proposal-export-namespace-from',
                            'react-native-reanimated/plugin',
                            '@babel/plugin-transform-flow-strip-types',
                            [
                                '@babel/plugin-transform-private-methods',
                                { loose: true },
                            ],
                        ],
                    },
                },
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'public/index.html'),
        }),
        process.env.ANALYZE && new BundleAnalyzerPlugin(),
    ].filter(Boolean),
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendor: {
                    test: /[\/]node_modules[\/]/,
                    name: 'vendors',
                    chunks: 'all',
                },
            },
        },
    },
});

module.exports = config;

My final chunks are:

Assets: 
  main.d4d5a64793bc974cb170.js (2.05 MiB)
  vendors.e9f736b3a31c46ef0971.js (9.08 MiB)
Entrypoints:
  main (11.1 MiB)
      vendors.e9f736b3a31c46ef0971.js
      main.d4d5a64793bc974cb170.js

MS office outlook addin js assets not being updated when deployed

I tried updating the the addin code. I believe ms caches some of these assets but I have waited multiple days and tried multiple redeployments. To this day I believe that the code still hasn’t been updated due to incorrect url requests still being present.

I have tried redeploying the addin and updating the code multiple times without success. I could tell because the url requests we’re still wrong. I have also tried updating the addin ID in the manifest and that didn’t work either.

Code Issues & Don’t allow drop into a Div

I’m currently trying to replicate the game “Sortieren” by the german Tv show “Schlag den Raab”.
I want to have two Divisions. One, where all the terms are listed. And the other one where they are supposed to be dragged into the right order.
The first problem I am encountering is being able to drop one term into another. Also, I tried fixing it by looking at:
prevent drop inside a child element when drag & dropping with JS
but it does not seem to work for me.
I am not sure what I’m missing here.
Problem 2:
Also, I cant seem to drag them into the right order.
Problem 3, apparently:
I tried rewriting the code, and now I cant seem to make the Drag and Drop work – at least not where they’re supposed to go.

I am not very experienced in coding so i scavenge from various sources. I am not quite sure whether it’s the script or something in the html causing problems.

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
#sortieren {
  float: left;
  width: 20%;
  height: 1000px;
  margin: 10px;
  padding: 10px;
  border: 1px solid black;
}

#higher {
  float: center;
  width: 88%;
  height: 15px;
  margin: 10px;
  padding: 10px;
  border: 1px solid black;
  text-align: center;
}

#dropper {
  float: center;
  width: 88%;
  height: 500px;
  margin: 20px;
  border: 1px solid black;
}

#lower {
  float: center;
  width: 88%;
  height: 15px;
  margin: 10px;
  padding: 10px;
  border: 1px solid black;
  text-align: center;
}

#Begriffe {
  float: right;
  width: 75%;
  height: 1000px;
  border: 1px solid black;
  margin: 10px;
  padding: 10px;
  justify-content: center;
}

.sort1 {
  background-image: linear-gradient(92.88deg, #455EB5 9.16%, #5643CC 43.89%, #673FD7 64.72%);
  border-radius: 16px;
  border-style: none;
  box-sizing: border-box;
  color: #FFFFFF;
  cursor: pointer;
  flex-shrink: 0;
  font-family: "Inter UI", "SF Pro Display", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  font-size: 16px;
  font-weight: 500;
  height: 4rem;
  padding: 0 1.6rem;
  text-align: center;
  text-shadow: rgba(0, 0, 0, 0.25) 0 3px 8px;
  transition: all .5s;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  margin: 50px
}

.sort1:hover {
  box-shadow: rgba(80, 63, 205, 0.5) 0 1px 30px;
  transition-duration: .1s;
}

@media (min-width: 768px) {
  .sort1 {
    padding: 0 2.6rem;
  }
}
<div id="sortieren">
  <div id="higher" draggable="false">Higher</div>
  <div id="dropper" ondrop="drop(event)" ondragover="allowdrop(event)">
    <div class="sort1" draggable="true" ondragstart="drag(event)" ondrop="return false" ondragover="return false" id="drag4">Moonlanding</div>
  </div>
  <div id="lower" draggable="false">Lower</div>
</div>

<div id="Begriffe" ondrop="drop(event)" ondragover="allowdrop(event)">
  <div class="sort1" draggable="true" ondragstart="drag(event)" ondrop="return false" ondragover="return false">Moonlanding</div>
  <div class="sort1" draggable="true" ondragstart="drag(event)" ondrop="return false" ondragover="return false">Moonlanding 23</div>
  <div class="sort1" draggable="true" ondragstart="drag(event)" ondrop="return false" ondragover="return false">Moonlanding 44</div>
</div>

Dealing with wrong currency calculation in Javascript

I have an app that deals with basic currency calculation in node.js and react.js. We are dealing with the usual operations of multiplication, addition, subtraction and division. I have noticed that when dealing with longer operations, I tend to lose maybe 4 cents which usually happen when calculation results to decimal numbers during the operation.
Take a look at this code:

 const currencyCalculation = (amount, actionValue, operationSign)=>{

  const expression = /[^0-9 .-]/g;

  const amountToString = amount?.toString();
  const filteredNum = amountToString.replace(expression, "");
  const m = new Intl.NumberFormat(undefined, {
  style: "currency",

  currency: "USD",
  minimumFractionDigits: 2,
 }).format(Number(filteredNum) operationSign actionValue);

 const finalResult = m?.replace(expression, "");

 return finalResult;

 };

The operationSign value can be + | - | *
Look at this example, we have a system where users pay deposit before checking out and the rest of the balance is spread out across different dates to be paid in installments.
Now, let say we have a total amount like this $8975.4; and our deposit sum is $398;
First, I subtracted the 398 from the total sum which is 8975.4. The answer would be 8577.4 which is correct. The user has 19 months to pay the rest of the balance which means I would divide the balance by 19 to get the amount they would pay per month.
So, we have 8577.4/ 19. All of these operations happen with the above currencyCalculation function. The division returned to 451.44 per month for 19 months.
I wanted to cross check if adding each months due sum all together plus the deposit sum would give me the exact total sum of the order and I discovered that I would be losing 4 cents across the process.
So, 451.44 * 19 gave me 8577.36 and adding the 398 deposit to it returned 8975.36 instead of 8975.4 which is basically $8975.40. How do I deal with issues like this? Is it possible to always get the accurate amount back during installment payment like this? I would prefer to have surplus than shorting values.
Please help me with proper steps to take.

NodeJs: Connect to usbstor driver device

I have an usb device that works as a physical drive using the USBSTOR driver.

I need to open a connection with that device and send some commands to it.

I can find the device using node-usb package, listing the Legacy USB devices. But when I try to open the interface I get an error. This is apparently because this package only works with WinUSB driver.

Do you know an other package or a way I can connect to this device using node js?

Best regards

How to setup a column menu button next to the header?

I’m working on a table that should have a column filter. This filter should be a multi select but since I don’t want to use the native <select> element ( because it’s intuitive and difficult to style ) I tried to create my own menu component.

Since this HTML code will be executed inside a container of an external system it’s not possible to embed third party libraries ( e.g. components ) so I have to use plain HTML, CSS and JS.

This is what I have so far

function toggleMenu(buttonElement) {
  buttonElement.parentNode.getElementsByClassName("menu-content")[0].classList.toggle("hidden");
}

function toggleOption(optionElement) {
  optionElement.classList.toggle("selected");

  // !!!For testing purposes only!!!
  console.log(optionElement.parentNode.getElementsByClassName("option selected"));
}
.menu {
  position: relative;
}

.menu-content {
  position: absolute;
  z-index: 1;
}

.hidden {
  display: none;
}

.selected {
  background: gray;
}

table,
th,
td {
  border: solid 1px black;
  border-collapse: collapse;
}

th {
  min-width: 500px;
}
<div>
  other content goes here
</div>

<table>
  <thead>
    <tr>
      <th>Col 1</th>
      <th>
        Col 2
        <span class="menu">
          <button onclick="toggleMenu(this)">Filter</button>
          <div class="menu-content hidden">
            <div class="option selected" onclick="toggleOption(this)">Selectable option 1</div>
            <div class="option selected" onclick="toggleOption(this)">Selectable option 2</div>
            <div class="option selected" onclick="toggleOption(this)">Selectable option 3</div>
          </div>
        </span>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Val 1</td>
      <td>Val 2</td>
    </tr>
  </tbody>
</table>

<div>
  other content goes here
</div>

I think it’s working as expected, but I need help with the CSS of the menu content. As you can see the container is not aligned with the button. How can I fix this?

If my approach can be improved ( e.g. simplified ) please let me know! 🙂

How can I change the body to the class name of a div [closed]

I can’t work out how to change the script so a div’s background color will change instead of the whole page background. My div class is “main1”. Any suggestions welcome.

var parseColor=function(r,o,t){return[r[0]+t*(o[0]-r[0])|0,r[1]+t*(o[1]-r[1])|0,r[2]+t*(o[2]-r[2])|0,r[3]&&o[3]?r[3]+t*(o[3]-r[3])|0:1]},daytimeColor=function(r,o,t){var e,n=(t=t||new Date).getHours();return"rgba("+parseColor(r,o,n*t.getMinutes()/1440).join()+")"},start=[150,225,255],end=[50,50,255];document.body.style.backgroundColor=daytimeColor(start,end);

Tried

document.getElementById("main1").style.backgroundColor = daytimeColor(start, end);

and

main1.style.backgroundColor = daytimeColor(start, end);

but still not working

Inserting data in the database using node.js and phpmyadmin

I need to store all the class information in the database(phpmyadmin) which the user would be sending to the server. However, it doesn’t store anything. Well, the id and the username has been successfully sent but the class infos were not. And by the way, the type of value of class information is object/json.

This is my backend code:

// create class function
exports.createclass = (req, res) => {
    console.log("Session user:", req.session.user); // Debug line

    if (!req.session.user) {
        return res.status(401).json({ message: 'User not authenticated' });
    }
    
    const { subjectCode, subjectTitle, section, year, term, semester } = req.body;
    const userId = req.session.user.id; // Assuming 'id' is saved in session data

    // Fetch the username based on the user ID
    db.query('SELECT username FROM users WHERE id = ?', [userId], (err, result) => {
        if (err) {
            console.error("User retrieval error:", err);
            return res.status(500).json({ message: 'Error retrieving user' });
        }
        if (result.length === 0) {
            return res.status(404).json({ message: 'User not found' });
        }

        const username = result[0].username;

        // Insert the class data into the 'classes' table
        db.query(
            'INSERT INTO classes (user, class) VALUES (?, ?)',
            [username, JSON.stringify({ subjectCode, subjectTitle, section, year, term, semester })],
            (error, results) => {
                if (error) {
                    console.error("Database error:", error);
                    return res.status(500).json({ message: 'Database error' });
                }
                res.json({ message: 'Class created successfully!' });
            }
        );
    });
};

This is my front-end code:

create.addEventListener('click', async () => {
   const subjectCode = classDiv.querySelector(".subjCodeInput")
   const subjectTitle = classDiv.querySelector(".subjTitleInput")
   const section = classDiv.querySelector(".sectionInput")
   const year = classDiv.querySelector(".yearInput")
   const term = classDiv.querySelector(".termInput")
   const semester = classDiv.querySelector(".semesterInput")
   const studentData = classDiv.querySelector('.fileUpload');

   const classInformation = [subjectCode.value.trim(),
                             subjectTitle.value.trim(), 
                             year.value.trim(),
                             section.value.trim(), 
                             term.value.trim(), 
                             semester.value.trim(), 
                             studentData.files.length > 0];

   
   for (let classinfo of classInformation) {
     let alertShown = false;
       if (!classinfo) {
           alertShown = true;
           setTimeout(() => alert('All fields require an input.'), 500);
           return; // Stop execution if any field is empty
       }
   }

   // If all fields are filled, create a class
   try {
       const classData = { 
           subjectCode: subjectCode.value.trim(), 
           subjectTitle: subjectTitle.value.trim(), 
           section:section.value.trim(), 
           year:year.value.trim(), 
           term:term.value.trim(), 
           semester:semester.value.trim() 
        };

       console.log(classData);

       const response = await fetch('/createclass', {
           method: 'POST',
           headers: { 'Content-Type': 'application/json' },
           credentials: 'include', // Important for maintaining session cookies
           body: JSON.stringify(classData)
       });

       if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
       }
       console.log(response);
       const result = await response.json();
       alert(result.message);  // Display a success message
       // Optionally, you can display the created class in the UI
       const listItems = document.createElement("div");
       listItems.classList = "listItemsStyle";
       listItems.innerHTML = `
            <p id="subjkode">${subjectCode.value.trim()}</p>
            <p id="subjectTitle">${subjectTitle.value.trim()}<p>
            <div class="p--items--middle">
               <p>${year.value.trim()}</p>
               <p>${section.value.trim()}</p>
               <p>${term.value.trim()}<p>
               <p>${semester.value.trim()}</p>
            </div>
            <div class="classBtns">
               <button class="approvalStatus">NO STATUS</button>
               <button class="openClass"><a href="/openclass">OPEN</a></button>
               <button class="deleteClass"><img src="/images/delete.png"></button>
            </div>`;  

       createClassContainer.appendChild(listItems);

       // Clear input fields after successful addition
       classDiv.querySelector(".subjCodeInput").value = "";
       classDiv.querySelector(".subjTitleInput").value = "";
       classDiv.querySelector(".sectionInput").value = "";
       classDiv.querySelector(".yearInput").value = "";
       classDiv.querySelector(".termInput").value = "";
       classDiv.querySelector(".semesterInput").value = "";
       classDiv.style.display = "none";
   } catch (error) {
       console.error('Error:', error);
   }
});
}

How do I colorize the area only under the timeseries line?

Using D3 JS, I am making a timeseries plot, and trying to colorize the area only under the timseries line. The code below adds horizontal colored blocks, first, below the green threshold, second between the green and red threshold, and the last, over the red threshold, but I would like the color only to be the added to the area falling under the timeseries line, whereas the areas over the timeseries line should appear white (no colors).

I googled but couldn’t find a working example or tutorial to achieve this. Can someone suggest a working example?

Update

I found this example, but it is different than what i would like to achieve.

Simple example using D3 Js

// Generate realistic dummy data for y axis (1 day, hourly)
const hours = d3.range(0, 24);
const values = Array.from({
  length: 24
}, () => Math.random() * 45);

const data = hours.map((hour, index) => ({
  hour,
  value: values[index]
}));

const margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 800 - margin.left - margin.right,
  height = 400 - margin.top - margin.bottom;

const svg = d3.select("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

const x = d3.scaleLinear()
  .domain(d3.extent(data, d => d.hour))
  .range([0, width]);

const y = d3.scaleLinear()
  .domain([0, d3.max(data, d => d.value)])
  .range([height, 0]);

const xAxis = d3.axisBottom(x).tickFormat(d => `${d}h`);
const yAxis = d3.axisLeft(y);

svg.append("g")
  .attr("transform", `translate(0,${height})`)
  .call(xAxis)
  .append("text")
  .attr("fill", "#000")
  .attr("x", width / 2)
  .attr("y", margin.bottom - 10)
  .attr("text-anchor", "middle")
  .style("font-size", "13px")
  .style("font-weight", "bold")
  .text("Hours");

svg.append("g")
  .call(yAxis)
  .append("text")
  .attr("fill", "#000")
  .attr("transform", "rotate(-90)")
  .attr("x", -height / 2)
  .attr("y", -margin.left + 10)
  .attr("text-anchor", "middle")
  .style("font-size", "13px")
  .style("font-weight", "bold")
  .text("Values");

const line = d3.line()
  .x(d => x(d.hour))
  .y(d => y(d.value));

// Calculate percentiles
const sortedValues = values.slice().sort((a, b) => a - b);
const percentile25 = d3.quantile(sortedValues, 0.25);
const median = d3.median(sortedValues);

// Add background rectangles
svg.append("rect")
  .attr("class", "background-blue")
  .attr("x", 0)
  .attr("y", y(percentile25))
  .attr("width", width)
  .attr("height", height - y(percentile25));

svg.append("rect")
  .attr("class", "background-lightgreen")
  .attr("x", 0)
  .attr("y", y(median))
  .attr("width", width)
  .attr("height", y(percentile25) - y(median));

svg.append("rect")
  .attr("class", "background-maroon")
  .attr("x", 0)
  .attr("y", 0)
  .attr("width", width)
  .attr("height", y(median));

// Add the line
svg.append("path")
  .datum(data)
  .attr("class", "line")
  .attr("d", line);

// Add threshold lines
svg.append("line")
  .attr("class", "threshold threshold-25")
  .attr("x1", 0)
  .attr("x2", width)
  .attr("y1", y(percentile25))
  .attr("y2", y(percentile25));

svg.append("line")
  .attr("class", "threshold threshold-50")
  .attr("x1", 0)
  .attr("x2", width)
  .attr("y1", y(median))
  .attr("y2", y(median));
.line {
  fill: none;
  stroke: black;
  stroke-width: 2px;
}

.threshold {
  stroke-width: 2px;
  stroke-dasharray: 4;
}

.threshold-25 {
  stroke: green;
}

.threshold-50 {
  stroke: red;
}

.background-blue {
  fill: blue;
  opacity: 0.1;
}

.background-lightgreen {
  fill: lightgreen;
  opacity: 0.1;
}

.background-maroon {
  fill: maroon;
  opacity: 0.1;
}
<script src="https://d3js.org/d3.v7.min.js"></script>

<svg width="800" height="400"></svg>

How do I set window height to 35px for an installed PWA?

For an installed PWA, I am unable to set the height of the window (using window.resizeTo) to 35px.

It would appear the minimum height is 108px. The titlebar is 35px so 108px seems strange to me. I am using Chrome on Windows 10.

I have no content and have tried: html, body { height: 0; min-height: 0 }.

Any ideas on how to resize the window to the height of the titlebar so just the titlebar is visible?

EDIT: You can manually resize the window such that only the titlebar is visible.

How do you type check injected child component in svelte?

I was wondering if you could do a type check on a child component that is injected into a parent component in Svelte?

So for example, if I wanted to do the following, but where the child is only allow to be of the type of the ChildRight component and not of another component like ChildWrong.

I have researched a little and concluded that you can either use <slot> or <svelte: component> to inject another component. A solution to either method would be useful.

Using slot

Parent.svelte

<div style="width: 500px; height: 500px; background-color: red;">
    <slot></slot>
</div>

App.svelte

<script>
    import Parent from "./Parent.svelte"
    import ChildRight from "./Child-right.svelte"
    import ChildWrong from "./Child-wrong.svelte"
</script>

<Parent>
    <ChildRight />
</Parent>

Using svelte:

Parent.svelte

<script lang=ts>
    export let childElement;
</script>


<div style="width: 500px; height: 500px; background-color: red;">
    <svelte:component this={childElement} />
</div>

App.svelte

<script>
    import Parent from "./Parent.svelte"
    import ChildRight from "./Child-right.svelte"
    import ChildWrong from "./Child-wrong.svelte"
</script>

<Parent childElement={ChildRight} />

So just to clarify, the following should give a type error

Using slot

<script>
    import Parent from "./Parent.svelte"
    import ChildRight from "./Child-right.svelte"
    import ChildWrong from "./Child-wrong.svelte"
</script>

<Parent>
    <ChildWrong />
</Parent>

Using svelte:component

<script>
    import Parent from "./Parent.svelte"
    import ChildRight from "./Child-right.svelte"
    import ChildWrong from "./Child-wrong.svelte"
</script>

<Parent childElement={ChildWrong} />

I have come by one solution using svelte:component, where I hardcode the type check. This does not seem like a preferable solution though

<script lang=ts>
    import ChildRight from "./Child-right.svelte"
    export let childElement;
</script>


<div style="width: 500px; height: 500px; background-color: red;">
    {#if childElement === ChildRight}
        <svelte:component this={childElement} />
    {:else}
        <p>ERROR IN CHILD TYPE</p>
    {/if}
</div>