Declaring multiple TypeScript variables with the same type
Asked Answered
H

12

99

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"?

Heliozoan answered 11/12, 2015 at 20:48 Comment(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.Abutting
W
116

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

Welladvised answered 11/12, 2015 at 21:13 Comment(2)
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.Heliozoan
Alternatively, for those in denial :) #34232815Tawnyatawsha
P
28

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.

Putupon answered 12/9, 2018 at 2:4 Comment(0)
A
19

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 
Anatolia answered 13/5, 2020 at 8:46 Comment(1)
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)Coitus
D
11

You have to specify the type on each variable:

let x: number, y: number
Declivitous answered 16/7, 2020 at 9:9 Comment(0)
M
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
Mesmerize answered 2/8, 2017 at 13:8 Comment(2)
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] = ....Fillin
I feel like this is anti-programming, and not in the spirit of the original question.Incidental
T
2

This is another alternative I use.

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

export type CoordinatesAway = CoordinatesHome;
Tawnyatawsha answered 26/4, 2021 at 14:21 Comment(0)
A
1
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
Anceline answered 18/5, 2020 at 6:57 Comment(0)
D
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> // ❌
Denigrate answered 16/4 at 5:43 Comment(0)
C
-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;
        }
    }  
Carmoncarmona answered 4/2, 2019 at 23:43 Comment(1)
that is not true, the isFormSaved will have "any" typeMirella
E
-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

Eddings answered 17/9, 2020 at 1:29 Comment(0)
B
-4

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

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

Beard answered 8/2, 2019 at 13:9 Comment(2)
Where's the type declaration?Freshman
@Freshman implicit type from valueMirella
O
-7

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

Orchidaceous answered 18/9, 2016 at 6:13 Comment(1)
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.Libnah

© 2022 - 2024 — McMap. All rights reserved.