在Typescript中定义自定义类型时,我想说如果没有定义内部元素,那么将使用默认值。
所以例如:
function custom(a:{required:string, optional='haha'}) {
}
这不起作用:(
我无法使用type
,因为该语法也不起作用。找到要使用的正确语法会很高兴。
答案 0 :(得分:-1)
TypeScript支持这一点,我认为代码最能解释它:
//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;
}
}
粘贴到https://www.typescriptlang.org/play/并玩游戏:)