代码之家  ›  专栏  ›  技术社区  ›  AhammadaliPK

Typescript:不能将默认参数值设置为false

  •  0
  • AhammadaliPK  · 技术社区  · 7 年前

    initializeInteraction(opts: { type?: string; freehand?:boolean= false }) {
        this._draw = this.drawService.initDraw({ drawtype: opts.type });
        this._drawInteraction = this._draw.interaction;
        this.mapService.addVector(this._draw.vector);
        this.mapService.addInteraction(this._drawInteraction);
      } 
    

    我想设置 freehand true false ,

    但当我宣布

    initializeInteraction(opts: { type: string; freehand?:boolean= false }) {}
    

    我得到一个错误作为

    [ts] A type literal property cannot have an initializer. [1247]
    
    3 回复  |  直到 6 年前
        1
  •  7
  •   Muhammed Albarmavi    7 年前

    您只需要设置默认值freehand无需 ?

    function initializeInteraction(type: string, freehand: boolean = false) {
     console.log(type,freehand);
     // your magic
    }
    
    initializeInteraction('something');
    initializeInteraction('something', false);
    initializeInteraction('something', true);
    

    将参数作为对象的唯一优点是可以按不同的顺序传递它们

    function initializeInteraction(opt:{ type:string , freehand?:boolean}) {
      let { type, freehand = false } = opt;
      console.log(type,freehand); 
      // your magic
    }
    

    function initializeInteraction({type,freehand=false }: {type:string,freehand?:boolean}) {
      console.log(type,freehand);
      // your magic
     }
    

    initializeInteraction({ type: 'something', freehand: false });
    initializeInteraction({freehand: false, type: 'something' });
    initializeInteraction({type: 'something' });
    

    两种方法都会得到相同的结果,但它们调用initializeInteraction的方式不同

    f('') ,f('',true) ({type:'',freehand:true}) f({freehand:true,type:''}) , f({type:''})

        2
  •  1
  •   Hayden Hall    7 年前

    你真的需要打包吗 type freehand 在空中 opts

    我建议:

    initializeInteraction(type: string, freehand?: boolean = false) {
        this._draw = this.drawService.initDraw({ drawtype: type });
        this._drawInteraction = this._draw.interaction;
        this.mapService.addVector(this._draw.vector);
        this.mapService.addInteraction(this._drawInteraction);
    }
    

    将为当前的 initializeInteraction

    另一种选择是使用重载。。。

    initializeInteraction(type: string);
    initializeInteraction(freehand: boolean);
    initializeInteraction(type: string, freehand: boolean);
    initializeInteraction(param1: string | boolean, param2: boolean = false) {
        //type checking and implementation here...
    }
    

    这将允许您单独传递一个值,或同时传递两个值。

        3
  •  0
  •   Vincent    7 年前
    { type: string; freehand?: boolean = false }
    

    接口 因此不能提供默认值。幸运的是 freehand 默认情况下未定义(错误)。

    你可以放心地用

    initializeInteraction(opts: { type?: string; freehand?:boolean }) {
        // ...
        if (opts.freehand) {
            // Do stuff
        }
    }
    
    推荐文章