Argument of type 'X' is not assignable to parameter of type 'X'

TypescriptVisual Studio-Code

Typescript Problem Overview


Good day. I'm new to Type Script, using VSCode.

Getting following errors:

  1. > error TS2322: Type '() => string' is not assignable to type 'string'.

  2. > error TS2322: Type '() => number' is not assignable to type 'number'.

The Code:

DTO.ts

interface DTO {
	
	getId(): number;
	getValue(): string;
}
export = DTO;

LinkedObject.ts

class LinkedObject {
        
    public value: string = "Not Set";
    public id: number = 0;
    
    constructor(value?: string, id?: number) {
        this.value = value;
        this.id = id;
    }
}
export = LinkedObject;

I am trying to instantiate LinkedObject class using above mentioned interface methods:

TravelClientFormPopulator.ts

class TravelClientFormPopulator {

    public populateComboBoxUsingDTOs(dataObjects: Array<DTO>, comboBoxID: string): void {
	
	    // Get the combo box
	    var selectElement = <HTMLSelectElement> document.getElementById(comboBoxID);
	    // Reset the options 
	    selectElement.options.length = 0;
	
	    var linkedObjectsToAdd: LinkedObject[] = new Array<LinkedObject>();
	
	    var defaultLinkedObject: LinkedObject = new LinkedObject("Not Selected", 0);
	
	    linkedObjectsToAdd.push(defaultLinkedObject);
	
	    for (var i = 0; i < dataObjects.length; i++) {
		    var value: string = dataObjects[i].getValue; // Error here
		    var id: number = dataObjects[i].getId; // And here
		    var linkedObject: LinkedObject = new LinkedObject(value, id);
	    }
    }
}

Any help will be highly appreciated.

Typescript Solutions


Solution 1 - Typescript

You miss parenthesis:

var value: string = dataObjects[i].getValue(); 
var id: number = dataObjects[i].getId();

Solution 2 - Typescript

For what it worth, if anyone has this problem only in VSCode, just restart VSCode and it should fix it. Sometimes, Intellisense seems to mess up with imports or types.

Related to https://stackoverflow.com/q/37500125/689429

Solution 3 - Typescript

Also adding other Scenarios where you may see these Errors

>1. First Check you compiler version, Download latest Typescript compiler > to support ES6 syntaxes

> 2. typescript still produces output even with typing errors this doesn't > actually block development,

When you see these errors Check for Syntaxes in initialization or when Calling these methods or variables,
Check whether the parameters of the functions are of wrong data Type,you initialized as 'string' and assigning a 'boolean' or 'number'

For Example

1.

 private errors: string;
    //somewhere in code you assign a boolean value to (string)'errors'
    this.errors=true
    or 
    this.error=5

2.

 private values: Array<number>;    
    this.values.push(value);  //Argument of type 'X' is not assignable to parameter of type 'X'

The Error message here is because the Square brackets for Array Initialization is missing, It works even without it, but VS Code red alerts.

private values: Array<number> = [];    
this.values.push(value);

Note:
Remember that Javascript typecasts according to the value assigned, So typescript notifies them but the code executes even with these errors highlighted in VS Code

Ex:

 var a=2;
 typeof(a) // "number"
 var a='Ignatius';
 typeof(a) // "string"

Solution 4 - Typescript

I'm doing angular 2 and typescript and I didn't realize I had a space in my arrow notation

I had .map(key = > instead of .map(key =>

Definitely keep your eyes open for stupid syntax errors

Solution 5 - Typescript

In my case, it was that I had a custom interface called Item, but I imported accidentally because of the auto-completion, the angular Item class. Be sure that you're importing from the right package.

Solution 6 - Typescript

I was getting this one on this case

...
.then((error: any, response: any) => {
  console.info('document error: ', error);
  console.info('documenr response: ', response);
  return new MyModel();
})
...

on this case making parameters optional would make ts stop complaining

.then((error?: any, response?: any) => {

Solution 7 - Typescript

For scenarios where this error could not be avoided, we can @ts-ignore the error.
In my case I had to pass a string param to isNaN whose ts definition only allow param of number type.

// @ts-ignore: Argument of type 'string' is not assignable to parameter of type 'number'.
 if (isNaN(myParam)) { // myParam is of string type 
      throw new Error('myPram should be a number');
 }
// but isNaN can accept string params too in javascript
isNaN(123) //false
isNaN('123') //false
isNaN(NaN) //true
isNaN('NaN') //true

Solution 8 - Typescript

In my case, strangely enough, I was missing the import of the class it was complaining about and my IDE didn't detect it.

Solution 9 - Typescript

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

Solution 10 - Typescript

you just use variable type any and remove these types of problem.

error code :

  let accessToken = res;
  localStorage.setItem(LocalStorageConstants.TOKEN_KEY, accessToken);

given error Argument of type '{}' is not assignable to parameter of type 'string'.

success Code :

  var accessToken:any = res;
  localStorage.setItem(LocalStorageConstants.TOKEN_KEY, accessToken);

we create var type variable then use variable type any and resolve this issue.

any = handle any type of value so that remove error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSashaView Question on Stackoverflow
Solution 1 - TypescriptMartyIXView Answer on Stackoverflow
Solution 2 - TypescriptMaximeBernardView Answer on Stackoverflow
Solution 3 - TypescriptIgnatius AndrewView Answer on Stackoverflow
Solution 4 - TypescriptMike KelloggView Answer on Stackoverflow
Solution 5 - TypescriptGusSLView Answer on Stackoverflow
Solution 6 - TypescriptAgorillaView Answer on Stackoverflow
Solution 7 - TypescriptViraj SinghView Answer on Stackoverflow
Solution 8 - TypescriptartemisianView Answer on Stackoverflow
Solution 9 - TypescriptSachin MishraView Answer on Stackoverflow
Solution 10 - Typescriptnagender pratap chauhanView Answer on Stackoverflow