【问题标题】:How to define default values in typescript type如何在打字稿类型中定义默认值
【发布时间】:2016-12-25 06:19:43
【问题描述】:

在 Typescript 中定义自定义类型时,我想说如果未定义内部元素,则将使用默认值。

例如:

function custom(a:{required:string, optional='haha'}) {

}

这不起作用:(

我不能使用type,因为该语法也不起作用。找到要使用的正确语法会很好。

【问题讨论】:

    标签: typescript typescript1.8


    【解决方案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/ 并玩转:)

    【讨论】:

    • myCustomType 不可用。加上 hte 问题在解构中:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2019-02-27
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多