Typescript interface default values

前端 未结 10 2080
借酒劲吻你
借酒劲吻你 2020-12-02 14:44

I have the following interface in TypeScript:

interface IX {
    a: string,
    b: any,
    c: AnotherType
}

I declare a variable of that t

10条回答
  •  孤街浪徒
    2020-12-02 15:39

    While @Timar's answer works perfectly for null default values (what was asked for), here another easy solution which allows other default values: Define an option interface as well as an according constant containing the defaults; in the constructor use the spread operator to set the options member variable

    interface IXOptions {
        a?: string,
        b?: any,
        c?: number
    }
    
    const XDefaults: IXOptions = {
        a: "default",
        b: null,
        c: 1
    }
    
    export class ClassX {
        private options: IXOptions;
    
        constructor(XOptions: IXOptions) {
            this.options = { ...XDefaults, ...XOptions };
        }
    
        public printOptions(): void {
            console.log(this.options.a);
            console.log(this.options.b);
            console.log(this.options.c);
        }
    }
    

    Now you can use the class like this:

    const x = new ClassX({ a: "set" });
    x.printOptions();
    

    Output:

    set
    null
    1
    

提交回复
热议问题