如何在打字稿类型中定义默认值
问题描述:
在打字稿中定义自定义类型时我想说如果未定义内部元素,则将使用默认值。如何在打字稿类型中定义默认值
因此,例如:
function custom(a:{required:string, optional='haha'}) {
}
这不工作:(
我不能使用type
因为这句法也不工作这将是很好的找到正确的语法使用。
答
打字稿支持这一点,我想代码将最好的解释:
//You can set defaults for variables
var defaultingString: string = "Default"
//You can create custom types through classes
var myCustomType: TestClass;
class TestClass {
//You can set defaults for variables in classes too
testVarA: string = "Default";
//You can handle it in a class constructor
//(which can also have defaults in it's parameters)
testVarB: string;
constructor(public someParam: string = "DefaultParam") {
if (!this.testVarB){
this.testVarB = someParam;
}
}
//Works in regular functions both for parameters and return type
testFoo (someOtherParam: string = this.testVarA): string {
return someOtherParam;
}
}
myCustomType不可用。另外hte问题在解构之内:( –