𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝘆𝗽𝗲𝘀 𝗗𝗲𝗺𝘆𝘀𝘁𝗶𝗳𝗶𝗲𝗱

TypeScript relies on a type system. Mastering it is your first step to writing better code.

Basic Types

TypeScript uses types similar to JavaScript primitives: • string: For text. • number: For all numbers (integers and floats). • boolean: For true or false values.

Type Inference

You do not always need to write the type. TypeScript often guesses the type based on the value you provide. This is called inference.

A good rule: • Let TypeScript infer types for local variables. • Write explicit types for function parameters and return types.

Arrays and Tuples

Arrays hold multiple values of the same type. • Example: let tags: string[] = ["ts", "js"];

Tuples are arrays with a fixed length and specific types for each position. • Example: let user: [string, number] = ["Ramesh", 31];

Union Types

Use union types when a value can be more than one type. • Example: let id: string | number = "abc123";

Special Types

Four types often confuse beginners:

  1. any This turns off type checking. It makes your code act like plain JavaScript. Use this as a last resort.

  2. unknown This is the safe version of any. It says the value could be anything, but you must check the type before you use it.

  3. void Use this for functions that do not return a value.

  4. never Use this for functions that never finish, such as those that throw errors or run infinite loops.

Summary for your workflow: • Use primitives for most data. • Use inference to keep code clean. • Use union types for flexible inputs. • Avoid any. • Use unknown instead of any when you are unsure.

Source: https://dev.to/ramesh_s_a8f0867d239e927c/typescript-types-demystified-simple-types-special-types-and-type-inference-5bf0