110

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 like to declare x and y as numbers with something like "x, y: number". But the compiler doesn't like that or anything else I've tried. Is there a better alternative to "x: number; y: number"?

1
  • 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. Commented Feb 8, 2018 at 1:45

12 Answers 12

125

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That's a shame. For web components with a lot of variables, declaring each on a separate line is a pain. This is especially true for form-based components.
Alternatively, for those in denial :) stackoverflow.com/questions/34232315/…
29

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.

Comments

23

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 

1 Comment

Using this answer, we can even initialize every variables at once. The drawback being having to count them manually : let [x, y]: number[] = Array(2).fill(1)
14

You have to specify the type on each variable:

let x: number, y: number

Comments

3

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

2 Comments

You can eliminate the orphan variable by doing var [n1,n2,n3,n4] = [] as number[]; but I'm still not a fan of this approach because whether with your code, or with my modification, tsc generates 4 useless assignments for the line var [n1,n2,n3,n4] = ....
I feel like this is anti-programming, and not in the spirit of the original question.
3
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

Comments

2

This is another alternative I use.

export type CoordinatesHome = {
    lat?: number;
    long?: number;
};

export type CoordinatesAway = CoordinatesHome;

Comments

0

you can accomplish this using typescript's satisfies operator

// module1.ts
export const a = 'asdf'
export const b = 'qwer'
// module2.ts
import * as Module1 from './module1'
Module1 satisfies Record<string, string> // ✅
Module1 satisfies Record<string, number> // ❌

Comments

-1

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;
        }
    }  

1 Comment

that is not true, the isFormSaved will have "any" type
-2

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

Comments

-4

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

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

2 Comments

Where's the type declaration?
@mustaccio implicit type from value
-7

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

1 Comment

This does not explicitly define signatureTypeName as a string; it is implicitly a string because that is the type of the first value assigned to it. You could initially assign anything to signatureTypeName and it would compile. For example, you could have done let a: string = "", b = 4, which defeats OP's question, where he/she stated they want both variables to be the same type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.