Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 类型';字符串|未定义';不可分配给类型';字符串';_Javascript_Typescript - Fatal编程技术网

Javascript 类型';字符串|未定义';不可分配给类型';字符串';

Javascript 类型';字符串|未定义';不可分配给类型';字符串';,javascript,typescript,Javascript,Typescript,我从TypeScript开始,遇到以下问题: 我有一个更新数据库中记录的方法,定义如下: class Category { update (data: ICategory & { id: string }): Promise<ICategory & { id: string }> { // Do Stuff } } interface ICategory { id?: string name: string, icon: string,

我从TypeScript开始,遇到以下问题:

我有一个更新数据库中记录的方法,定义如下:

class Category {
  update (data: ICategory & { id: string }): Promise<ICategory & { id: string }> {
    // Do Stuff
  }
}

interface ICategory {
  id?: string
  name: string,
  icon: string,
  iconColor: string
}
即使我检查了
typeof obj.id==“string”
我仍然会有相同的错误

我怎样才能解决这个问题?正如我所说,我现在从TypeScript开始,所以欢迎任何建议

谢谢

您可以使用:

接口数据{
id:字符串;
}
函数测试(args:FuncData){}
接口部分数据{
id?:字符串;
}
常量数据:PartialData={id:'test'};
函数funcDataGuard(数据:PartialData):数据是FuncData{
返回data.id!=null;
}
if(funcDataGuard(数据)){
试验(数据);
}

您如何调用此方法?错误来自于什么代码?@VLAZ我按如下方式调用:
category.update(this.form)
,表单对象如下:
form:{id:undefined,name:'',icon:'iconColor:'}
然后我看不到问题<代码>id不是字符串。这正是该方法想要防止的。@VLAZ,对不起,我的错误,实际上当我调用该函数时,所有字段都已填充。例如:
图标:“adb”,图标颜色:“00a3a3”,id:“CTMJOII3ZBF3CYETXWT”,名称:“测试”
TS2345: Argument of type 'ICategory' is not assignable to parameter of type 'ICategory & { id: string; }'.
  Type 'ICategory' is not assignable to type '{ id: string; }'.
    Types of property 'id' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.