Johnny Johnny
Johnny Johnny

Reputation: 329

What is the point of using types when declaring a variable in Typescript?

I'm newbie in Typescript, and I know its great benefits when working with big apps and teams : )

Let's suppose I have this TypeScript:

declare const num = 5: number;

Why is that better than:

const num = 5

Should I explicitly declare (with type) simple variables always in TypeScript?

Fortunately, the variable’s type is inferred from the data type of the value. So can I use normal JS (like in the second example)?

Upvotes: 3

Views: 6048

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370679

When declaring a variable, if the type of what you're assigning to it can be understood correctly by the TS compiler, then there's no need to define its type. In many cases, declaring an explicit type is not necessary, such as with const num = 5. But sometimes it is necessary, such as when declaring a variable which will be assigned to later, but not now:

let someData: MyData;

Otherwise, someData will be typed as any, which isn't type-safe.

Another example for when it would be useful would be when creating an array which will later be pushed to:

const arr: number[] = [];
// later:
arr.push(5);

The compiler can't infer at arr's declaration what values the array may contain, so number[] should be included when defining arr. (Otherwise, it'll be typed as any[], and any is not type-safe and should be avoided when possible)

Whenever TS can infer the type of a variable correctly and automatically - and most of the time, it can - then feel free to leave off the explicit note of the variable type, since it doesn't help.

Note that declare does something completely different - using that keyword tells TS that a variable with that name is defined in the current scope by other code, such as by a library. Variables which are declared will not exist in emitted code. Unless you have a library or something which defines a variable that Typescript doesn't understand exists, you almost certainly don't want to use declare.

Upvotes: 13

Damien
Damien

Reputation: 1600

You are using typescript to avoid wrong value assignment. For instance, typescript will throw an error when you try to use a string for a number variable.

let num: number = 5;

You can't change it to num = "this is a string";. Typescript will throw a type error.

Upvotes: 0

Related Questions