Steps to resolve the issue of 'type is not assignable to any' while working with a member

I'm facing an issue with a code snippet like the one below:

interface IFoo {
  bar: string;
  baz: number;
}

function f(foo: IFoo, name: 'bar' | 'baz', val: any) {
  foo[name] = val;   // <<< error: Type 'any' is not assignable to type 'never'.
}

Surprisingly, when I change the type of "baz" to also be "string", the error disappears:

interface IFoo {
  bar: string;
  baz: string;
}

function f(foo: IFoo, name: 'bar' | 'baz', val: any) {
  foo[name] = val;   // fine
}

I am curious about the reason behind this behavior and whether there's a solution that doesn't involve changing name: 'bar' | 'baz' to name: string.

Answer №1

It is essential to verify that the data stored in val matches the data type expected for the corresponding name.

Experience Typescript with this Example

interface IFoo {
  bar: string;
  baz: number;
}

function f<K extends keyof IFoo>(foo: IFoo, name: K, val: IFoo[K]) {
  foo[name] = val;
}

const foo: IFoo = {
    bar: '',
    baz: 0
}

f(foo, 'bar', 'abc')
f(foo, 'baz', 1)
console.log(foo);

You can also make it more generic.

function f<T, K extends keyof T>(foo: T, name: K, val: T[K]) {
  foo[name] = val;
}

Try out the Playground Example

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

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Creating a grid UI in AngularJS using Typescript: utilizing functions as column values

I am working on an AngularJS app that includes the following UI grid: this.resultGrid = { enableRowSelection: true, enableRowHeaderSelection: false, enableHorizontalScrollbar: 0, enableSorting: true, columnDefs: [ { name: &apos ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Is it possible to execute user-defined functions dynamically in a Node.js application without having to restart the server

I am exploring the potential for allowing users to insert their own code into a Node application that is running an express server. Here's the scenario: A user clicks 'save' on a form and wants to perform custom business validations. This ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

Using ES6 and Typescript, when a button is clicked, apply a class to all TD elements within the button except for the first one. No need for jQuery

A sample table structure is shown below: <table> <tr> <td>1</td> <td>joe</td> <td>brown</td> <td><button onclick="addClasses()">Add Class to add TD's in t ...

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

Creating a JSON object from an array of data using TypeScript

This might not be the most popular question, but I'm asking for educational purposes... Here is my current setup: data = {COLUMN1: "DATA1", COLUMN2: "DATA2", COLUMN3: "DATA3", ..., COLUMNn: "DATAn"}; keyColumns = ["COLUMN2", "COLUMN5", "COLUMN9"]; ...

Is it possible for a typed function to access object properties recursively?

Is there an efficient method in TypeScript to type a function that can recursively access object properties? The provided example delves two levels deep: function fetchNestedProperty<T, K extends keyof T>(obj: T, prop1: K, prop2: keyof T[K]) { r ...

What method can be used to specify a function of any signature that returns a particular type in programming?

I am looking to define a unique type that must be a function which, when executed, will always produce an object containing the property type: string. The input parameters for this function are of no concern. For instance: foo(1, 'bar'); // res ...

Exploring the usage of arrays within Angular 4 components. Identifying and addressing overlooked input

I'm struggling with array declaration and string interpolation in Angular 4 using TypeScript. When I define the following classes: export class MyArrayProperty { property1: string; property2: string; } export class MyComponent { @Input() object: ...

Applying a Typescript Generic to enhance the functionality of the API fetcher

I've written a simple function to enhance fetch functionality. I am currently exploring how TypeScript Generics can be utilized to define the Type for 'data' in the return. const apiFetchData = async ( url: string, options = {}, ): P ...

Typescript struggling to comprehend the conditional rendering flow

I am facing an issue with the code snippet below: import * as React from 'react' type ComponentConfig = [true, {name: string}] | [false, null] const useComponent = (check: boolean): ComponentConfig => { if (check) { return [true, {name ...

Error encountered in spyOn TS when passing array iteration instead of a string

Instead of repeating test cases with minor adjustments, I have implemented an Array and iterated through it. However, I am encountering a TS error in test when passed from the Array instead of as a string testLink Error: No overload matches this call. ...

Encountering an issue while compiling with TypeScript, where a typescript class that involves Meteor and Mongo is throwing an error stating "Property 'Collection' does not exist on type 'typeof Mongo'."

During the compilation of Meteor, an error in the console states "Property 'Collection' does not exist on type 'typeof Mongo'." I'm curious if anyone has encountered this issue before and how they resolved it. I am working with me ...

Stop MatDialog instance from destroying

In my application, I have a button that triggers the opening of a component in MatDialog. This component makes API calls and is destroyed when the MatDialog is closed. However, each time I open the MatDialog for the second time by clicking the button agai ...

Make Ionic 2 Navbar exclusively utilize setRoot() instead of pop()

When navigating to a different page, the ion-navbar component automatically includes a back button that uses the pop() method to return to the previous page. Is there a way to modify this behavior so that it utilizes the setRoot() method instead of pop(), ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...