TypeScript: how to declare array of fixed size for type checking at Compile Time

前端 未结 3 1315
生来不讨喜
生来不讨喜 2021-01-17 10:19

Update: These checks are meant for compile time, not at runtime. In my example, the failed cases are all caught at compile

3条回答
  •  星月不相逢
    2021-01-17 11:18

    Here is a simple example of a class to control the length of its internal array. It isn't fool-proof (when getting/setting you may want to consider whether you are shallow/deep cloning etc:

    https://jsfiddle.net/904d9jhc/

    class ControlledArray {
    
      constructor(num) {
        this.a = Array(num).fill(0); // Creates new array and fills it with zeros
      }
    
      set(arr) {
        if (!(arr instanceof Array) || arr.length != this.a.length) {
          return false;
        }
        this.a = arr.slice();
        return true;
      }
    
      get() {
        return this.a.slice();
      }
    
    }
    
    $( document ).ready(function($) {
    
      var m = new ControlledArray(3);
    
      alert(m.set('vera')); // fail
      alert(m.set(['vera', 'chuck', 'dave'])); // pass
    
      alert(m.get()); // gets copy of controlled array
    
    });
    

提交回复
热议问题