Common Types In TypeScript

[!INFO]-
topic: πŸ¦’ TypeScript
links: Basic syntax to define a variable with a type in TypeScript
source: TypeScript course by the native web
tags: #permanent-noteΒ #published

Last Modified: =dateformat(this.file.mtime, "MMM. dd, yyyy - HH:mm")


Basic Types

Common types in TypeScript are

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

Arrays

You can define an array like this:

let primes: number[];
primes = [2, 3, 5];

or like this:

let primes: Array%3Cnumber%3E;

But the latter has problems with JSX/TSX in React. So use the first one.

Enums

Enums can be used to give a selection of values.

enum Color {
	Red,
	Green,
	Blue
}
let color: Color = Color.Green;

Unknown

This is a wildcard type that works similar to normal JavaScript, but it still has type safety, so it tries to defer the current type. This can result in not allowing you to call a function that you know is there because TypeScript doesn't know.

let something: unkonwn;
something = 23;      //this 
something = 'Hello'; // is 
something = true;    // valid

Any

Any behaves in the same way as unkown, but without type safety. So, you can call anything and do anything, like in normal JavaScript.

let something: any;
something = 23;      //this 
something = 'Hello'; // is 
something = true;    // valid
```>)````