解构对象以匹配函数预期参数接口

时间:2017-11-30 10:44:41

标签: typescript

我有以下接口,功能和对象:

export interface GetCountyArgs {
  id?: number;
  title?: string;
}

export interface County {
  id: number;
  title: string;
  locationSet: [];
}

function myFunc(a:GetCountyArgs){
    console.log(a.id, a.title)
}

let county: County = {id:1, title:"Galway", locationSet:null};

我正在寻找一个速记,如果它存在的话,要解构'County'对象以匹配'GetCountyArgs'接口,因为我将它传递给'myFunc'。

使用以下解构语法可以在多行中实现:

let x: GetCountyArgs;
({...county} = x);

myFunc(x)

但是,我将以这种方式使用接口,并且想知道在调用方法时是否有办法内联。我觉得应该有,但找不到任何例子......

干杯!

2 个答案:

答案 0 :(得分:1)

您可以使用Object.assign从x复制到国家/地区:

Object.assign(county, x);

或者,如果您不介意创建新对象:

county = {
    ...county,
    ...x
};

答案 1 :(得分:1)

任何至少具有数字或字符串属性ID的对象都与 myFunc 兼容:

myFunc({});
myFunc({ id: 2 });
myFunc({ title: "2" });
myFunc({ title: "2", id: 3 });

根据tsconfig中定义的类型检查标志,myFunc将仅拒绝 GetCountyArgs 中未定义属性的文字对象:

//does not type check
myFunc({ title: "2", id: 3, "stillWorks?": "no"}); // "stillWorks?" is not defined in the interface but...
//this way does.
var butThisWayDoes =  { title: "2", id: 3, "stillWorks?": "no" };
myFunc(butThisWayDoes);// it will not complain when passing a variable

因此,在这种情况下不需要进行解构,并且您不需要声明GetCountyArgs类型的变量,它不是仅对结构有用的名称。如果对象在变量中只传递变量,如果用文字调用该函数,则不要在文字中放入任何未在界面中定义的属性