Introduction to TypeScript
In this article, we will learn how to use TypeScript and its basic features.
What is TypeScript?
- TypeScript is a superset of JavaScript that compiles to plain JavaScript.
- Add basically static typing to JavaScript.
Why use TypeScript?
- avoid unexpected errors and results.
- reduce the amount of bugs.
- reduce the amount of time to fix bugs.
- IDE support.
Types
Below is a list of basic types in TypeScript.
boolean true/false
string 'foo', "foo", `foo`
number int, float, hex, binary
array type[]
array Array<string | number> // union type of string and number
tuple (type[number,string])
enum key and value
enum colors {
withe = '#fff'
black = '#000'
}
any (any type)
void () does not return anything
null | undefined
never (never type) no return type
object {}
Type Inference
The own typescript infers the type when passed a simple value.
let message = 'Hello World'; // let message: string
message = 123; // error: type number is not assignable to string
const isActive = true; // const isActive: boolean
const count = 10; // const count: number
const list = [1, 2, 3]; // const list: number[]
const user = {
name: 'John',
age: 30,
}; // const user: { name: string; age: number }
user.name = 123; // error: type '123' is not assignable to type 'string'
Type Aliases and Interfaces
- Type Aliases:
Type aliases are used to create a new name for an existing type and can be reused.
type StringType = string;
type StringOrNumber = StringType | number; // union type of string and number
type StringOrNumber = {
id: number;
value?: string; // optional property
};
const value: StringType = 'foo'; // no error
const value2: StringType = 123; // error: type '123' is not assignable to type 'string'
const value3: StringType = true; // error: type 'boolean' is not assignable to type 'string'.
- Interfaces:
Similar to the type alias but it only works with objects and is more for creating more complex objects.
Use interface for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via declaration merging if some definitions are missing. - TypeScript Docs
interface Game {
id: string | number; // union type of string and number
title: string;
genre: string
discription: string;
platform?: string[]; // optional property
}
Difference between interface and type aliases
You can find more information about interfaces and type aliases in the official TypeScript documentation. - TypeScript Docs
Thank you for reading this article.
If you enjoy this article, please up vote and comment.
Follow me on Twitter
Top comments (0)