【发布时间】:2016-12-25 06:19:43
【问题描述】:
在 Typescript 中定义自定义类型时,我想说如果未定义内部元素,则将使用默认值。
例如:
function custom(a:{required:string, optional='haha'}) {
}
这不起作用:(
我不能使用type,因为该语法也不起作用。找到要使用的正确语法会很好。
【问题讨论】:
在 Typescript 中定义自定义类型时,我想说如果未定义内部元素,则将使用默认值。
例如:
function custom(a:{required:string, optional='haha'}) {
}
这不起作用:(
我不能使用type,因为该语法也不起作用。找到要使用的正确语法会很好。
【问题讨论】:
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/ 并玩转:)
【讨论】: