Declaring multiple TypeScript variables with the same type

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

    How about this? Using array deconstruction with Typescript's array type.

    let [x,y]: number[]
    

    But please note that this feature is unsafe if you do not turn on pedantic index signature check. For example, the following code will not have compile error even though it should:

    let [x, y]: number[] = [1]
    console.log(x.toString()) // No problem
    console.log(y.toString()) // No compile error, but boom during runtime 
    
    0 讨论(0)
  • 2020-12-10 00:46

    There isn't any syntax that would accomplish this in a better way than just writing the type twice.

    0 讨论(0)
  • 2020-12-10 00:48

    Not recommended, but:

    interface Name {[name:string]: T } or type Name{[name:string]: T}
    

    example: type test = {[Name: string]:string}

    example: interface {[Name: string]:boolean}

    This works. An example is provided in the Typescript documentation for another use case. Typescript Handbook

    0 讨论(0)
  • 2020-12-10 00:50

    Just adding that even if you do the following:

    let notes, signatureTypeName: string;
    

    it still does not work. In this case, notes is declared as type any and signatureTypeName as type string. You can verify all this by simply hovering over the variable, for example in Visual Studio Code. The declared type appears then in a popup.

    0 讨论(0)
  • 2020-12-10 00:51

    Array destructuring can be used on both side to assign values to multipel

    [startBtn, completeBtn, againBtn] = [false, false, false];

    0 讨论(0)
  • 2020-12-10 00:58

    You have to specify the type on each variable:

    let x: number, y: number
    
    0 讨论(0)
提交回复
热议问题