Declaring multiple TypeScript variables with the same type

后端 未结 11 1281
半阙折子戏
半阙折子戏 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:00

    There is no real way to achieve what you want. If your only goal is to compress everything onto one line, you can do the following:

    public AcccountNumber: number;public branchCode:number;
    

    …but I wouldn't recommend it.

    0 讨论(0)
  • 2020-12-10 01:03
    let [string1, string2]: string[] = [];
    

    breaking it down:

    • on the left the whole [string1, string2] is declared as string[], implying string1, string2 is of type string
    • to do a destructure you need it to be assigned to something, here empty array []
    • on right hand the empty array is [undefined, undefined, undefined, ...] when destructuring string1 and string2 gets assigned to undefined
    • finally string1, string2 are of type string with value undefined
    0 讨论(0)
  • 2020-12-10 01:03

    let notes: string = '', signatureTypeName = '';

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-10 01:07

    e.g. let isFormSaved, isFormSubmitted, loading: boolean = false; this syntax only works in function block, but not outside of it in typescript export class file. Not sure why is that.

    For Example:

    export class SyntaxTest {
    
    public method1() {
        e.g. let isFormSaved, isFormSubmitted, loading: boolean = false;
    }
    

    }

    0 讨论(0)
提交回复
热议问题