How to conditionally set a TypeScript property based on another nested property?

I have the following types:

type Settings = {
    enableAdvancedFeature?: boolean;
};

type Options = {
    settings?: Settings;
    enforceAdvancedOrder?: boolean;
};

I want to make the enforceAdvancedOrder property a boolean only when settings.enableAdvancedFeature is true.

If settings.enableAdvancedFeature is false or undefined, then enforceAdvancedOrder should be undefined.

Here’s an example of the desired behavior:

const validOption1: Options = {
    settings: { enableAdvancedFeature: true },
    enforceAdvancedOrder: true,
};

const validOption2: Options = {
    settings: { enableAdvancedFeature: false },
    enforceAdvancedOrder: undefined, // enforceAdvancedOrder should be undefined
};

const invalidOption: Options = {
    settings: { enableAdvancedFeature: false },
    enforceAdvancedOrder: true, // This should cause a TypeScript error
};

I tried defining a conditional type for Options but couldn’t figure out how to enforce this dependency between the nested properties.

How can I define the Options type to achieve this behavior while keeping it type-safe? Any suggestions would be greatly appreciated!

My Test dome solution has not been passed even my solution returns correct answers

I’m trying to solve one of the test dome questions in javascript but even my solution returns correct output , I’m not able to pass the 3 tests , only the first one has been passed successfully … , I dont know actually , is there any criteria that my solution hasn’t meet even it returns correct output .

here is the link of test :
test dome question

And here is my solution u can test it directly and see the result

function canTravelTo(gameMatrix, fromRow, fromColumn, toRow, toColumn) {
  // Then check bounds
  if (
    fromRow < 0 ||
    fromColumn < 0 ||
    toRow < 0 ||
    toColumn < 0 ||
    fromRow >= gameMatrix.length ||
    fromColumn >= gameMatrix[0].length ||
    toRow >= gameMatrix.length ||
    toColumn >= gameMatrix[0].length
  ) {
    return false;
  }

  // check if they start or end with false (land)
  else if (
    gameMatrix[fromRow][fromColumn] === false ||
    gameMatrix[toRow][toColumn] === false
  ) {
    return false;
  }

  // check horizontally
  else if (fromRow === toRow) {
    const specificArray = gameMatrix[fromRow].slice(fromColumn, toColumn + 1);
    const row = specificArray;

    row.pop();
    row.shift();

    if (row.includes(false)) {
      console.log("boat can't move horizontally and faced some obstacles");
      return false;
    }

    console.log("boat moved horizontally without obstacles");
  }

  // check vertically
  else if (fromColumn === toColumn) {
    const mergedArray = [];
    for (let i = fromRow + 1; i < toRow; i++) {
      mergedArray.push(gameMatrix[i]);
    }

    const result = mergedArray.some((row) => row[fromColumn] === false);

    if (result) {
      console.log("boat can't move vertically and faced some obstacles");
      return false;
    }

    console.log("boat moved vertically without obstacles");
    return true;
  } else {
    return true;
  }

  return true;
}


test dome output

Autocompletion for imports not working as expected in Nextjs project

All of a sudden for some reason, auto completion seems to be acting weird in my Nextjs-Typescript project. I am using VsCode. Anyone else encountered similar issue?

The import should simply be next/link
enter image description here

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "downlevelIteration": true,
    "useUnknownInCatchVariables": false,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

Can I build AND run a TypeScript ExpressJS service in Vercel

I’m experimenting with Vercel and want to run a TypeScript ExpressJS service there. There are plenty of turorials and I have something running. However, I am not happy with the way it’s configured:

{
    "version": 2,
    "outputDirectory": "dist",
    "builds": [
        {
            "src": "dist/index.js",
            "use": "@vercel/node",
            "config": { "includeFiles": ["dist/**"] }
        }
    ],   
    "routes": [
        {
            "src": "/(.*)",
            "dest": "dist/index.js"
        }
    ]
}

This requires me to checkin the compiled JavaScript to the project’s repo, which feels wrong as it’s all generated code. If I switch to Vercel building the JavaScript on deployment, which is ideally what I want:

{
    "version": 2,
    "outputDirectory": "dist",
    "buildCommand": "npm run build",
    "routes": [
        {
            "src": "/(.*)",
            "dest": "dist/index.js"
        }
    ]
}

then Vercel returns the JavaScript in the index.js file rather than executingstrong text it. I assumed there must be a way to add:

“use”: “@vercel/node”,

to the build configuration, but if there is I can’t find it or work out.

Is there a way to achieve what I want or am I stuck with checking-in generated JavaScript?

Coin change – A test case is failing

The problem goes like this:

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Here’s how I try to solve. But it fails for this test case:
[195,265,404,396], amount 3239
Appreciate any help.

var coinChange = function(coins, amount) {
    let ans = Infinity;
    var helper = function(coins, amount, index=0, coinsNeeded = 0){
        if(amount === 0){
            ans = Math.min(ans, coinsNeeded);
            return;
        }
        if(index >= coins.length) return;

        if(coins[index] > amount) return;
        if(amount % coins[index] === 0){
            ans = Math.min(ans, coinsNeeded + amount / coins[index]);
        }

        helper(coins, amount-coins[index], index, coinsNeeded+1);
        helper(coins, amount, index+1, coinsNeeded);
        
    }

    helper(coins, amount);

    return ans === Infinity ? -1 : ans;
    
};

console.log(coinChange([1,2,5], 11))

Clarifications Needed for Azure AI Speech Service and Speech SDK in JavaScript

I am currently building a command-based voice assistant system using the Azure AI Speech Service and the Microsoft Azure Cognitive Services Speech SDK for JavaScript. Despite referring to the documentation, I have some clarifications that I need help resolving:

  1. Initially, I used the fromAuthorizationToken method to initialize the speech configuration. However, I encountered a few issues with this approach:

The token expires after 10 minutes, so I need to implement a token renewal mechanism.
The recognizer stops picking up speech after 10–20 seconds of silence, requiring me to refresh it and restart the session manually.
To address these issues, I switched to using the fromSubscription method, which seems to work better. With this method, the recognizer continues to pick up speech even after 10–20 seconds of silence. Could you explain the exact difference between the two methods and why fromSubscription behaves differently in this regard?

  1. Even after switching to the fromSubscription method, I still experience no response after prolonged silence. Is there a way to handle this issue more gracefully? Ideally, I’d like to capture an event from the recognizer indicating something like: “Hey, I didn’t detect any speech for a while. Do you want to continue or stop?”

Is there an existing mechanism or best practice for detecting and managing extended silence in the recognizer?

Any guidance or insights to resolve these issues would be greatly appreciated!

“show more” button that resizes container height

Question:
I have a container where a list of blog items are shown. I wish to only show excatly 2 items and hide the rest. how do I accomplish this?

Problem Description:
The items have dynamic height depending on font and screen sizes, so I can’t just do “height:20rem; overflow:hidden” for the container as that would look ugly. Is there a solution that makes the height of the container same as the height of two of it’s children plus some padding?

What I’ve tried:
I tired using grid template rows 2; overflow:hidden for the container and setting every children to row span 1. This does not hide anything. It seems that overflow:hidden only works when height is specified.

image with a container containing several blog items

Js. Create promise and handle errors and attach promise callbacks later

My goal is to make possible to attach handle callbacks later in time. I am not sure that code in my solution solves it because problem may be in some other place as a result of bed code (design) or lack of basic knowledge. My first version of Request and Response classes:

class Request {

  make(url, params) {
    let p = fetch(url, params)
      .then(this.doThing)
      .then(this.doAnotherThing);

    return new Response(p);
  }

  // methods like doThing and doAnotherThing ...

}

class Response {
  responsePromise;

  constructor(p) {
    this.responsePromise = p;
  }

  handle(success, failure) {
    this.responsePromise.then(success, failure);
  }
}

Usage example

let r = Request();
r.make('/order/update', { method: 'POST', body: {} }).handle((resposne) => { }, (error) => { });

But I want to catch errors inside make method because sometimes handle method can not catch errors in time due to later invocation.

My current solution is to create helper callbacks and put them inside promise:

class Request {

  make(url, params) {
    let p = fetch(url, params)
      .then(this.doThing)
      .then(this.doAnotherThing)
      .catch(this.errorHandler);

    return new Response(p);
  }

  doAnotherThing(response) {

    // some job
    return () => Promise.resolve(response);
  }

  errorHandler(error) {

    // some job
    return () => Promise.reject(error);
  }

}

class Response {
  responsePromise;

  constructor(p) {
    this.responsePromise = p;
  }

  handle(success, failure) {

    result = responsePromise.

    this.responsePromise.then(f => f()).then(success, failure);
  }
}

How to solve: Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema?

I have a working project React + typescript that works with Babel and Webpack. When I did a code along, It suddenly got this error:

“Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.”

I got this error when I was trying to integrate a .css file. What I did was installed the style and css loader and put it in my webpack.config.js file.

I don’t know what I am doing wrong. How do I get my styling to work?

webpack.config.js file:


const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
entry: path.resolve(__dirname, "..", "./src/index.tsx"),
resolve: {
  extensions: [".tsx", ".ts", ".js"]
},

module: {
  rules: [
    {
      test: /.(js|jsx|ts|tsx)$/,
      exclude: /node_modules/,
      use: [
        {
          loader: ["babel-loader", "ts-loader"]
        }
      ]
    },
    {
      test: /.(css|scss)$/,
      use: ["style-loader", "css-loader"]
    }
  ]
},
output: {
  path: path.resolve(__dirname, "..", "./dist"),
  filename: "bundle.js"
},
mode: "development",

plugins: [
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, "..", "./src/index.html")
  })
]
}

My devDependencies also says the css-loader and style-loader is installed.

package.json:


  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "cra-template-typescript": "1.2.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-scripts": "5.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.26.0",
    "@babel/preset-env": "^7.26.0",
    "@babel/preset-react": "^7.26.3",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.26",
    "babel-loader": "^9.2.1",
    "css-loader": "^7.1.2",
    "style-loader": "^4.0.0",
    "typescript": "^4.0.0",
    "webpack": "^5.97.1",
    "webpack-cli": "^6.0.1"
  },
  "scripts": {
    "start": "webpack serve --config webpack/webpack.config.js --open",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

And this is where I import the file

App.tsx file:


import "./styles.css"

export const App: React.FC = () => {
  return (
    <div>
      <h1>React typescript webpack starter </h1>
      <h3> Hier word uiteindelijk de cursus pagina gemaakt!</h3>
    </div>
  )
}

Socket io base URL

I’m using binance websocket url which is wss://stream.binance.com:9443/stream?streams=btcusdt@trade with WebSocket.

const websocket = new WebSocket("wss://stream.binance.com:9443/stream?streams=btcusdt@trade");

When I try to use socket.io-client instead of WebSocket, the url changes to https://stream.binance.com:9443/socket.io/?streams=btcusdt%40trade&EIO=4&transport=polling&t=bm42en7b and /socket.io is added to the url.

"socket.io": "^4.8.1",
"socket.io-client": "^4.8.1",

import io, { Socket } from "socket.io-client";

const socketIo = io("wss://stream.binance.com:9443/stream?streams=btcusdt@trade");

How can I prevent socket.io from changing the url?

JavaScript Not Loading In My HTML, CSS and JS Code Editor

I created a custom HTML, CSS and JS code editor. I noticed the editor is able to run HTML and CSS files but not JS files. Here is the code:

const html_code = document.querySelector('.html-code textarea');
const css_code = document.querySelector('.css-code textarea');
const js_code = document.querySelector('.js-code textarea');
const result = document.querySelector('#result');

function run() {
    // Storing data in Local Storage
    localStorage.setItem('html_code', html_code.value);
    localStorage.setItem('css_code', css_code.value);
    localStorage.setItem('js_code', js_code.value);

    // Executing HTML, CSS & JS code
    result.contentWindow.eval(localStorage.html_code);
    result.contentDocument.body.innerHTML = `<style>${localStorage.css_code}</style>` + localStorage.html_code;
    result.contentWindow.eval(localStorage.js_code);
}

// Checking if user is typing anything in input field
html_code.onkeyup = () => run();
css_code.onkeyup = () => run();
js_code.onkeyup = () => run();

Whenever I paste a code like this below into the HTML Text editor area, it will display the button with the Bootstrap styles but the Javascript JQuery won’t be loaded which made the dropdown button not to work.

<!DOCTYPE html>
<html>
<head>
  <title>Bootstrap Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container">                                          
  <div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
      Dropdown button
    </button>
    <div class="dropdown-menu">
      <a class="dropdown-item" href="#">Link 1</a>
      <a class="dropdown-item" href="#">Link 2</a>
      <a class="dropdown-item" href="#">Link 3</a>
    </div>
  </div>
</div>

</body>
</html>

Section doesn’t have the right position GSAP, ScrollTrigger

I just started experimenting with GSAP and ScrollTriggers. My goal is to make a little animation within a section.hero that stays pinned to the screen while doing the animation. Currently my issue is that the section that I put the animations in has a 900px translate on the Y axis, at the load of the page. When I scroll down and arrive at the end of the animation the 900px translate is removed and my section goes back to the top of the screen as I want it to and the animation works as expected. Why does my section.hero has such a big offset ?

HTML

<section class="hero">
    <div class="wrapper">
        <div class="title">
            <h1 class="left">Title</h1>
            <div class="right"></div>
        </div>
        <div class="title">
            <div class="left"></div>
            <h1 class="right">Title</h1>
        </div>
        <div class="title anim">
            <h1 class="left">Title</h1>
            <div class="right"></div>
        </div>
        <div class="title">
            <div class="left"></div>
            <h1 class="right">Title</h1>
        </div>
    </div>
</section>

JS

const scrollTrigger = {
      trigger: '.hero',
      scrub: 0.75,
      markers: true,
      pin: true,
      pinSpacing: false,
    };

    gsap.to('.left', {
      scrollTrigger: scrollTrigger,
      xPercent: -100,
      ease: 'none',
    });
    gsap.to('.right', {
      scrollTrigger: scrollTrigger,
      xPercent: 100,
      ease: 'none',
    });

I tried adding the pinSpacing: false to my JS but that didn’t work neither does having it to true.

React state not updating in DOM despite changes in useEffect for titles and artists props

I’m building a music player in React, and I’m trying to update the track title and artist dynamically using useEffect when the props (title, artist) change. However, while the values update correctly in the console log, they do not reflect in the DOM.

I am using state hooks (useState) for the title and artist, and I’ve ensured that the component should re-render when these states change. Despite this, the DOM still doesn’t update with the new values.

import React, { useEffect, useState } from 'react';
import { FaBackward, FaPlay, FaPause, FaForward, FaHeart, FaRandom, FaVolumeUp } from 'react-icons/fa';
import useAudio from '../Audio/useAudio';
import api from '../../Services/api';


const Playbar = ({ url, title, artist, id }) => {


    //url is the audio url
    //title is the title of the track
    //artist is the artist of the song
    //id is the id of the track
    const [playing, toggle] = useAudio(url);
    
    const [titles, setTitles] = useState(title || "");
    const [artists, setArtists] = useState(artist || "");

    // Update titles and artists when props change
    useEffect(() => {
        setTitles(title || "");
        setArtists(artist || "");
    }, [title, artist]);


    // Update current playing track in the database if playing is true and the track has changed
    useEffect(() => {
        if (playing) {
            api.post(`/api/currentplaying`, {
                playing: playing,
                title: titles,
                artist: artists,
                id: id
            });
        }
    }, [titles, artists, playing, id]);

    // Fetch current playing track from the database

    useEffect(() => {
        const fetchCurrentPlaying = async () => {
            try {
                const res = await api.get(`/api/fetchcurrentplaying/${id}`);
                if (res.data.current && res.data.current.length > 0) {
                    const currentTrack = res.data.current[0];
                    setTitles(currentTrack.title);
                    setArtists(currentTrack.artist);
                } else {
                    console.log("No current playing data found.");
                }
            } catch (error) {
                console.error('Error fetching current playing:', error);
            }
        };

        fetchCurrentPlaying();
    }, [id]);


    // Log when the playbar is updated
    useEffect(() => {
        console.log("Playbar updated with:", { url, title, artist });
    }, [url, title, artist]);

    return (
        <footer className="fixed text-white bottom-0 left-0 right-0 bg-gray-800 p-2 flex items-center">
            <div className="flex items-center">
                <img src="https://placehold.co/50x50" alt="Current song" className="rounded-full mr-4" />
                <div>
                    <p className="font-bold">{titles || "No Title"}</p>
                    {console.log("Title", titles)}
                    {console.log("Artist", artists)}
                    <p>{artists || "No Artist"}</p>
                </div>
            </div>
            <div className="flex-1 flex justify-center items-center">
                <FaBackward className="mx-4" />
                {playing ? (
                    <FaPause className="mx-4" onClick={toggle} />
                ) : (
                    <FaPlay className="mx-4 " onClick={toggle} />
                )}
                <FaForward className="mx-4" />
            </div>
            <div className="flex items-center">
                <FaHeart className="mx-4" />
                <FaRandom className="mx-4" />
                <FaVolumeUp className="mx-4" />
            </div>
        </footer>
    );
}

export default Playbar;

Problem:

The title and artist props are passed into the Playbar component, and the state variables titles and artists are updated accordingly inside a useEffect.
These state variables log correctly in the console (console.log), but the DOM is not reflecting the updated state values.
I’ve confirmed that the state is being updated in Console, but it doesn’t re-render the DOM as expected.

What I’ve tried:

I’ve used useEffect to update the state values when the props change.
I’m ensuring that setTitles and setArtists are called correctly.
I’m using React.memo for the Playbar component, but the issue persists.

Can anyone help me identify why the updated state values are not reflected in the DOM even though they are correctly logged?

useAudio.js

import { useState, useEffect } from 'react';

const useAudio = (url) => {
    const  = useState(new Audio(url));
    const [playing, setPlaying] = useState(false);

    const toggle = () => {
        setPlaying(prev => !prev);
    };

    useEffect(() => {
        const handleEnded = () => setPlaying(false);
        audio.addEventListener('ended', handleEnded);

        return () => {
            audio.pause();
            audio.removeEventListener('ended', handleEnded);
        };
    }, );

    useEffect(() => {
        if (url && url !== undefined) {
            const newAudio = new Audio(url);
            setAudio(newAudio);
            audio.src = url;
            setPlaying(true);
            
        }else{
            setPlaying(false);
        }
    }, [url]);

    useEffect(() => {
        if (playing && url) {            
            audio.play().catch(error => {
                console.error("Error playing audio:", error);
            });
        } else {
            audio.pause();
        }
    }, [playing, audio]);

    return [playing, toggle];
};

export default useAudio;

get image src then use it for div background javascript

        <div id="slides"></div>
        <div id="slidermenu">

    <img class="slidermenuimage" src="red.png" onclick="showslide()"/><br>
    <img class="slidermenuimage" src="orange.png" onclick="showslide()"/><br>
    <img class="slidermenuimage" src="yellow.png" onclick="showslide()"/><br>
        
        </div>
        
    <script>
        function showslide() {
            y = document.getElementById("slides");
            y.style.display = "block";
            z = this.src;
            y.backgroundImage = 'url('+z+')';
        }
        
    </script>

When someone clicks on one of these images i would like that image to appear as the background image of div “slides”, and am not sure what is going wrong. Maybe I am not using “this” properly.

SVG Glowing Text Effect Not Working on iPhone (ALL Browsers) — Unable to Apply text-shadow or Animation

On iOS (ALL Browsers), the glow effect (via text-shadow and animation) doesn’t render on SVG .
The same code works as expected on desktop browsers (Chrome, Edge) and Android browsers.
I’ve tried using -webkit prefixes and different methods of CSS for the glowing effect, but none work on iOS Browsersenter image description here.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG Glowing Text</title>
    <style>
        @keyframes glowAnimation {
            0% {
                text-shadow: 0 0 5px #bfff01cc, 0 0 10px #bfff01cc, 0 0 20px #bfff01cc;
            }
            50% {
                text-shadow: 0 0 10px #bfff01cc, 0 0 20px #ffffffcc, 0 0 30px rgba(230, 230, 230, 0.6);
            }
            100% {
                text-shadow: 0 0 5px rgba(255, 255, 255, 0.8), 0 0 10px rgba(255, 255, 255, 0.8), 0 0 20px rgba(230, 230, 230, 0.6);
            }
        }

        .glowing-text {
            font-size: 40px;
            font-family: 'Montserrat', sans-serif;
            text-align: center;
            animation: glowAnimation 2s infinite alternate;
        }

        svg {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <section id="home">
        <svg viewBox="0 0 200 100" width="100%" height="100%">
            <path id="curve" d="M 0 50 C 100 0 100 100 200 50" fill="none" />
            <text>
                <textPath xlink:href="#curve" startOffset="50%" text-anchor="middle" font-size="12" font-family="Montserrat" fill="#fff">
                    Legend Barber
                </textPath>
            </text>
        </svg>
    </section>
</body>
</html>

Using CSS text-shadow for the glowing effect:
It works fine on most browsers (desktop, Android) but doesn’t render on iOS Phones.
Using -webkit prefixes on CSS properties:
The prefix -webkit-filter and other -webkit changes had no effect.
Modifying the SVG text properties like font size, color, and path for better compatibility:
Still no glow effect on iOS Phones.