Let’s talk about types, Primitive types – Lesson 2

First Lesson was just a flash about TypeScript – today I will try to show you possible types and their valid and wrong values.

From specification:

TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development.

So we have this what in my opinion really miss in Javascript – strong typing!

In TypeScript types are categorized as primitive types, object types, union types, or type parameters;

Primitive types are:

  • number
  • boolean
  • string
  • any
  • void
  • null
  • undefined

Let’s see possible values for this types

number
boolean
string
any
void

As we can see, we can’t assign string to number or number to bool etc – so we finally get it!

Interesting detail is that we can declare variable as void – but we can’t assign value. Void types are for function and methods – just for information that we shouldn’t expect any return value;
From documentation:

We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters.

For every primitive we can assign undefined or null.

For all primitive types we have mother – any (like Object in Java).

That’s why it’s possible to assign different types to variable with static constraint any.

Let’s learn TypeScript – Lesson 1

Thanks to Javascript modern webpages are more interactive, more useful and more helpful – but JavaScript is not scripted Java …

JavaScript does no have strong typing – is this advantage or disadvantage? It depends …

For someone JS gives more freedom and faster way to code simple objects or arrays. It’s very nice for small apps, but after some time and many written apps we can miss restricted typing, code completion or smart refactoring in our favourite IDE.
Czytaj dalej