TypeScript: how to declare a fixed-size array for type checking at compile time

Refresh . These checks are for compile time , not runtime . In my example, failed cases are all caught at compile time, and I expect similar behavior for other should-fail cases .

Suppose I write a table class where I want all members of the class to be arrays of the same length, for example:

class MyClass {
  tableHead:  string[3]; // expect to be a 3 element array of strings
  tableCells: number[3]; // expect to be a 3 element array of numbers
}

The closest solution I have found so far:

class MyClass {
  tableHead:  [string, string, string];
  tableCells: [number, number, number];
}

let bar = new MyClass();
bar.tableHead = ['a', 'b', 'c']; // pass
bar.tableHead = ['a', 'b'];      // fail
bar.tableHead = ['a', 'b', 1];   // fail

// BUT these also pass, which are expected to fail at compile time
bar.tableHead = ['a', 'b', 'c', 'd', 'e']; // pass
bar.push('d'); // pass
bar.push('e'); // pass

Any better ideas?

+5
source share
3 answers

2: 3.4, , OP, ( Playground):

class MyClass {
  tableHead: readonly [string, string, string]
  tableCells: readonly [number, number, number]
}

1: 2.7, TypeScript .

, . TypeScript .

, , , . ,

type StringTriplet = [string, string, string]

:

const a: StringTriplet = ['a', 'b', 'c']

,

const [one, two, three, four] = a;

, , :

const [one, two, three] = a;

, , , , , map

const result = a.map(/* some pure function */)

, result 3 , 3. , , , . a

+4

. ( / , / ..:

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

});
0

Typescript: n-? , :

type Tuple<TItem, TLength extends number> = [TItem, ...TItem[]] & { length: TLength };

type Tuple9<T> = Tuple<T, 9>;
0

Source: https://habr.com/ru/post/1670757/


All Articles