注意:这已经过简化并在4/13/2017更新以反映TypeScript 2.1,请参阅TypeScript 1.8答案的历史记录 .
听起来您希望object参数是可选的,并且对象中的每个属性都是可选的 . 在示例中,如提供的那样,重载语法isn 't needed. I wanted to point out some bad practices in the some of the answers here. Granted, it'不是本质上写入 box = { x: 0, y: 87, width: 4, height: 0 } 的最小可能表达式,但是这提供了所有可能想要从类中描述的细节的代码 . 此示例允许您使用一个,一些,全部或没有参数调用函数,并仍然获取默认值 .
/** @class */
class Box {
public x?: number;
public y?: number;
public height?: number;
public width?: number;
// The class can work double-duty as the interface here since they are identical
// Alternately, reference your own interface, e.g.: `...BoxI = {} as BoxI`
constructor(obj: Box = {} as Box) {
// Define the properties of the incoming `obj` object here.
// Setting a default value with