Declaring multiple TypeScript variables with the same type

后端 未结 11 1332
半阙折子戏
半阙折子戏 2020-12-10 00:09

I\'m coding a large TypeScript class and I\'ve set noImplicitAny to true. Is there any way to declare multiple variables of the same type on the same line?

I\'d lik

11条回答
  •  悲哀的现实
    2020-12-10 01:07

    If you can accept an orphan variable. Array destructuring can do this.

    var numberArray:number[]; //orphan variable
    var [n1,n2,n3,n4] = numberArray;
    n1=123; //n1 is number
    n1="123"; //typescript compile error
    

    Update: Here is the Javascript code generated, when targeting ECMAScript 6.

    var numberArray; //orphan variable
    var [n1, n2, n3, n4] = numberArray;
    n1 = 123; //n1 is number
    

    JS Code generated when targeting ECMAScript 5, like Louis said below, it's not pretty.

    var numberArray; //orphan variable
    var n1 = numberArray[0], n2 = numberArray[1], n3 = numberArray[2], n4 = numberArray[3];
    n1 = 123; //n1 is number
    

提交回复
热议问题