typescript “X”类型的参数不能分配给“X”类型的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34738799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:52:35  来源:igfitidea点击:

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

typescriptvisual-studio-code

提问by Sasha

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

再会。我是 Type Script 的新手,使用 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'.

  1. 错误 TS2322:类型 '() => string' 不能分配给类型 'string'。

  2. 错误 TS2322:类型 '() => number' 不能分配给类型 'number'。

The Code:

编码:

DTO.ts

DTO.ts

interface DTO {

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

LinkedObject.ts

链接对象.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 LinkedObjectclass using above mentioned interface methods:

我正在尝试LinkedObject使用上述接口方法实例化类:

TravelClientFormPopulator.ts

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.

任何帮助将不胜感激。

采纳答案by Martin Vseticka

You miss parenthesis:

你错过了括号:

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

回答by MaximeBernard

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.

无论如何,如果有人仅在 VSCode 中遇到此问题,只需重新启动 VSCode 即可解决。有时,Intellisense 似乎与导入或类型混淆。

Related to Typescript: Argument of type 'RegExpMatchArray' is not assignable to parameter of type 'string'

Typescript相关:“RegExpMatchArray”类型的参数不可分配给“string”类型的参数

回答by Ignatius Andrew

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,

  1. 首先检查你的编译器版本,下载最新的 Typescript 编译器以支持 ES6 语法

  2. 即使输入错误,打字稿仍然会产生输出,这实际上并不会阻止开发,

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.

1.

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

2.

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.

这里的错误消息是因为缺少数组初始化的方括号,即使没有它也可以工作,但是 VS Code 会发出红色警报。

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

注意:
请记住,Javascript 根据分配的值进行类型转换,因此 typescript 会通知他们,但即使在 VS Code 中突出显示这些错误,代码也会执行

Ex:

前任:

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

回答by Mike Kellogg

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

我正在做 angular 2 和 typescript,但我没有意识到我的箭头符号中有一个空格

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

我有.map(key = >而不是.map(key =>

Definitely keep your eyes open for stupid syntax errors

绝对要睁大眼睛看愚蠢的语法错误

回答by Gustavo Sánchez

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.

就我而言,我有一个名为 Item 的自定义接口,但由于自动完成,我意外导入了 angular Item 类。确保您从正确的包中导入。

回答by nagender pratap chauhan

you just use variable type anyand remove these types of problem.

您只需使用变量类型any并消除这些类型的问题。

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.

我们创建 var 类型变量,然后使用变量类型 any 并解决此问题。

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

any = 处理任何类型的值,以便消除错误。

回答by Agorilla

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

在这种情况下,使参数可选将使 ts 停止抱怨

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

回答by Sachin Mishra

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......>>>>)

您可以使用 Number 对象并通过使用Number(<<<<...Variable_Name......>>>>)传递您的值以获得适当的结果

回答by artemisian

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

就我而言,奇怪的是,我错过了它抱怨的类的导入,而我的 IDE 没有检测到它。