repsweet080303 / typescript-learning

0 stars 0 forks source link

TypeScript for JavaScript Programmers #13

Open repsweet080303 opened 1 year ago

repsweet080303 commented 1 year ago

TypeScript for JavaScript Programmers

TypeScript stands in an unusual relationship to JavaScript.

TypeScript offers all of JavaScript’s features, and an additional layer on top of these: TypeScript’s type system.

Types by Inference

TypeScript can build a type-system that accepts JavaScript code but has types.

This offers a type-system without needing to add extra characters to make types explicit in your code.

Defining Types

There is already a small set of primitive types available in JavaScript: boolean, bigint, null, number, string, symbol, and undefined.

TypeScript extends this list with a few more, such as any (allow anything), unknown (ensure someone using this type declares what the type is), never (it’s not possible that this type could happen), void (a function which returns undefined or has no return value)

Composing Types

With TypeScript, you can create complex types by combining simple ones. There are two popular ways to do so: with unions, and with generics.

Unions: With a union, you can declare that a type could be one of many type

type MyBool = true | false;

A popular use-case for union types is to describe the set of string or number literals that a value is allowed to be:

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

For example, you can make a function return different values depending on whether it is passed a string or an array:

function wrapInArray(obj: string | string[]) {
  if (typeof obj === "string") {
    return [obj];

(parameter) obj: string
  }
  return obj;
}

Generics

Generics provide variables to types. A common example is an array. An array without generics could contain anything. An array with generics can describe the values that the array contains.

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

Structural Type System