ค้นหาเว็บไซต์

typescript1.8 - วิธีการกำหนดค่าดีฟอลต์ในชนิดของ TypeScript


เมื่อกำหนดประเภทที่กำหนดเองใน Typescript ฉันต้องการกล่าวว่าหากองค์ประกอบภายในไม่ได้ถูกกำหนด จะมีการใช้ค่าดีฟอลต์

ดังนั้นยกตัวอย่างเช่น:

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

}

นี่ใช้ไม่ได้ :(

ฉันไม่สามารถใช้ type ได้เพราะว่าสัณฐานวิธีนั้นก็ใช้งานไม่ได้เช่นกัน มันคงดีถ้าจะหาสัณฐานวิธีที่ถูกต้องมาใช้

คำตอบ #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/ แล้วลองเล่นดู :)

บทความที่เกี่ยวข้อง