Assigning properties of an object with a mix of data types dynamically in TypeScript

Imagine you have an object with properties that are of different types, and you need to assign a dynamic value to a property identified dynamically. While this is easily done in JavaScript, how can you accomplish the same in TypeScript without encountering the TS(2322) error 'not assignable to type 'never'', preferably without resorting to using 'any'?

Take a look at the sample code (playground here):

interface Film {
    name : string;
    durationInSeconds : number;
}
const myFunction = function(
    film: Film,
    filmPropertyName: keyof Film,
    newValue: string | number
) {
    let value = film[filmPropertyName];
    console.log('Existing value:', value);
    
    film[filmPropertyName] = newValue; 
    value = newValue; 
    
    if(typeof film[filmPropertyName] === typeof newValue) {
        value = newValue; 
        film[filmPropertyName] = newValue; 
    }
   
    if(typeof film[filmPropertyName] === 'string' && typeof newValue === 'string') {
        value = newValue; 
        film[filmPropertyName] = newValue; 
    }
}

In a simple scenario like this, one might suggest changing all properties to the same type, but in real-world scenarios where multiple types are required, this solution falls short.

Switching the type of the 'film' parameter to 'any' may resolve the error but could lead to other issues when passing data to other functions within the scope.

While casting before assignment eliminates the error, it compromises TypeScript's typechecking power, and adding 'any' annotations goes against the TypeScript methodology. How should you handle this situation?

Answer №1

To tackle the issue, you can incorporate a double-generic in the type signature as shown below, while maintaining all other components intact:

const myFunctionGeneric = function<K extends keyof Film, V extends Film[K]>(
    film: Film,
    filmPropertyName: K,
    newValue: V
) 

Check out the updated playground here.

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

What is the best way to programmatically organize a tree structure using an array containing parent-child configurations?

I am looking to restructure my JavaScript object into a hierarchical tree pattern object. Here is my current object: let input = [ {'id':1 ,'pid' : 0}, {'id':2 ,'pid' : 1}, {'id':3 ,'pid' : ...

Managing asset paths post ng build: A guide

I've been attempting to use assets to display svg icons on my ESRI map. I'm working with Angular9 and the esri js api, trying to add a symbol from a URL. Locally, the svg appears on the map, but once I build and deploy the project to IIS, it sta ...

What settings do I need to adjust in order to set up VSCode to be compatible with TypeScript

I'm currently struggling to set up VSCode with TypeScript and facing some difficulties. My focus is on the following: https://code.visualstudio.com/docs/languages/typescript It seems like after installing the compiler, VSCode should function proper ...

Can one specify a conditional return type in TypeScript without resorting to typecasting within the function's implementation?

I'm currently working on a function where the return type is determined by the input values, but I'm finding that typescript is requiring me to use the as keyword to address the issue I'm facing. Is there a more graceful way to handle this a ...

Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application. To import it, I allowed importing json by adding a few extra lines in tsconfig.json: { "compilerOptions": { "module": "commonjs", ...

Client cannot establish a connection to the database using the MongoDB driver

My node app crashes when I include the line of code: app.use('/api', routes). However, if I remove this line, the app runs without any issues. The error message displayed is: return db.collection(name) ^ TypeError: Cannot read properties of unde ...

What is the method for loading dynamic scripts within Angular?

Angular Version: 7.1.4 In an attempt to resolve the issue of script loading errors, specifically 'Uncaught TypeError: Can not read property Responsive' of undefined', I explored a potential solution which involved creating a service for ...

Can classes from an external package be imported into an Angular library within an Angular app using Openlayers?

I am currently developing an Angular library that configures an OpenLayers map as an Angular component. The component is functioning properly, but I need to access classes and constants from a package imported by the library, specifically OpenLayers. To w ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Create a flexible string for refining a REST request

I am currently working on constructing a dynamic string and I've encountered an issue, so I humbly seek assistance from the community. I have a string for creating a rest call filter, but I am struggling with the use of and's This query only fu ...

Ways to retrieve various elements produced by the ngFor directive in Angular

Is there a way to dynamically add CSS classes to div elements generated with *ngFor Angular directive? I initially attempted using @ViewChild directive and Renderer2, but encountered issues when working with multiple elements. Then, I explored manipulating ...

The k6.io library is unable to read binary files using the TextDecoder file because of a problem with the util

For my k6.io tests, I am trying to import TextDecoder from the util package. Within my script, I aim to read a binary file: import { sleep, check } from 'k6'; import { Options } from 'k6/options'; import http from 'k6/http'; ...

Tips for Invoking an Overloaded Function within a Generic Environment

Imagine having two interfaces that share some fields and another interface that serves as a superclass: interface IFirst { common: "A" | "B"; private_0: string; } interface ISecond { common: "C" | "D"; private_1: string; } interface ICommo ...

Viewer object in three.js with TypeScript destroyed after single rendering cycle

Currently, I am working on developing an object viewer that utilizes threejs and typescript. This component is integrated into a react service. Initially, everything functions as expected when initializing the viewer object and scene. However, after rende ...

Generate incorrect JSON for a negative test in TypeScript

Struggling with navigating TS (amazing) static typing to generate invalid data for a negative test scenario. I am currently working on resolving an issue where the client may pass invalid JSON (double quotes within the value). I believe I have fixed the i ...

Angular Dynamic Form Troubles

Recently, I followed a tutorial from https://angular.io/guide/dynamic-form to create a dynamic angular form. So far, everything has been working smoothly. However, I am now facing a challenge as I try to implement a question type where users can add more i ...

Tips for including type definitions when adding elements to an array in TypeScript

Having trouble avoiding the use of 'any' as the type definition when pushing elements into an array? I attempted to specify the type but encountered an error. Here is a snippet of the code: interface answerProps { state: string; answer: s ...

Receiving an error while passing properties to a React component: "Property 'firstName' is not found on type 'Readonly<{}>'."

As a beginner in React, I need some patience I'm attempting to create a simple component where users can input their first and last names, update the values, and see them displayed after clicking a button. However, I keep encountering TypeScript comp ...

Calculating the duration between a start date and an end date excluding holidays using JavaScript

Is there a way to calculate the difference in days between 2 dates without counting weekends and holidays? I've already figured out how to exclude weekends. export const workday_count = (start: moment.Moment, end: moment.Moment) => { const first ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...