Skip to content
Created: October 4, 2020

What is TypeScript? ​

ProjectDescription
EssenceSuperset of JavaScript
FunctionAdd type system to JS
Runtime❌ cannot be run directly and needs to be compiled into JS
Compilertsc
Core ValuesType Safety + IDE Smart Tips + Maintainability

In one sentence:

TS = Typed JavaScript

1. What problems does TypeScript solve? ​

One sentence:

TypeScript = JavaScript + Type System

Typical pain points of JS ​

js
function sum(a, b) {
  return a + b;
}

sum(1, "2"); // 🤯 运行时才发现是 "12"

TS improvements ​

ts
function sum(a: number, b: number): number {
  return a + b;
}

sum(1, "2"); // ❌ 编译期直接报错

TS Core Values

  • ❌ Avoid pitfalls (find mistakes in advance)
  • 🧠 Better code tips & auto-completion
  • 🔧 Refactoring is safer
  • 📐 More suitable for large projects (React/Vue3/Node)

2. Basic usage of TypeScript ​

1️⃣ Installation & Compilation (just understand it) ​

bash
npm install typescript -g
tsc index.ts

In most front-end projects:

  • Vite/Vue/React already have built-in TS support
  • You almost never have to run tsc manually

2️⃣ Common built-in tool types (must know) ​

Tool TypeFunction
Partial<T>Make optional
Required<T>Become required
Pick<T, K>Get some fields
Omit<T, K>Exclude fields
Record<K, T>key-value object
ts
type User = {
  id: number;
  name: string;
  age: number;
};

type UserBase = Pick<User, "id" | "name">;

3. Basic type (the most important) ​

  • JavaScript types are divided into two types: primitive data types (Primitive data types) and object types (Object types).
  • All primitive data types have no properties (property)
ts
let name = "hello ";
console.log(name.toUpperCase());

console.log(new String("hello ").toUpperCase());

When calling a primitive data type method, JavaScript will make a quick forced switch between the primitive data type and the object type.

ts
let isOK: boolean = true; // 编译通过
let isOK: boolean = Boolean(1); // 编译通过
let isOK: boolean = new Boolean(1); // 编译失败   期望的 isOK 是一个原始数据类型

1️⃣ Original type ​

ts
let a: number = 1;
let b: string = "hello";
let c: boolean = true;
let d: null = null;
let e: undefined = undefined;
let id: symbol = Symbol("unique");
let bigNumber: bigint = 123n;

2️⃣ Array ​

ts
let arr1: number[] = [1, 2, 3];
let arr2: Array<string> = ["a", "b"];

3️⃣ Tuple (fixed length + fixed type) ​

ts
let tuple: [string, number] = ["age", 18];

Commonly used for:

  • useState
  • Returns fixed structure data
tuplearray
Each item can be of different typesEach item is of the same type
Has predefined lengthNo length limit
Used to represent a fixed structureUsed to represent a list
ts
const animal: [string, number, boolean] = ["hello ", 10, true];

4️⃣ Enumeration (Enum) ​

ts
enum Status {
  Pending,
  Success,
  Error,
}

let s: Status = Status.Success;

// 普通枚举
enum Gender {
  GIRL,
  BOY,
}
console.log(`李雷是${Gender.BOY}`);
console.log(`韩梅梅是${Gender.GIRL}`);

// 常数枚举
enum Week {
  MONDAY = 1,
  TUESDAY = 2,
}
console.log(`今天是星期${Week.MONDAY}`);
  • The difference between constant enumerations and ordinary enumerations is that constant enumerations will be deleted during the compilation phase and cannot contain calculated members.
  • If calculated members are included, an error will be reported during the compilation phase.
ts
const enum Colors {
  Red,
  Yellow,
  Blue,
}

let myColors = [Colors.Red, Colors.Yellow, Colors.Blue];
const enum Color {
  Red,
  Yellow,
  Blue = "blue".length,
}

📌 In actual combat It is more recommended to use union type instead of enum (talk about it later)

4. Objects & Interfaces (most commonly used in front-end) ​

1️⃣ Write the object type directly ​

ts
const user: {
  name: string;
  age: number;
} = {
  name: "Tom",
  age: 18,
};

2️⃣ interface (strongly recommended) ​

ts
interface User {
  name: string;
  age: number;
  isAdmin?: boolean; // 可选
}

const u: User = {
  name: "Tom",
  age: 18,
};

Used extensively in React props / Vue props / API return values

3️⃣ interface vs type (note the conclusion first) ​

Comparisoninterfacetype
Object✅ Strong✅
United❌✅
extensionsextends&
React / VueCommonly usedCommonly used

5. Function type (must be known by the front end) ​

  • You can specify the type of parameters and the type of return value

1️⃣ Parameters & Return Value ​

ts
function add(a: number, b: number): number {
  return a + b;
}

no return value

ts
let hello2 = function (name: string): void {
  console.log("hello2", name);
  return undefined;
};
hello2("hello ");

2️⃣ Optional parameters & default values ​

  • In TS, the formal parameters and actual parameters of the function must be the same. If they are different, optional parameters must be configured, and they must be the last parameter.
ts
function greet(name: string, age?: number) {} // age为可选参数
function greet2(name: string, age = 18) {} // age设置了默认值

Optional parameters ​

ts
function print(name: string, age?: number): void {
  console.log(name, age);
}
print("hahaha ");

Default parameters ​

ts
function ajax(url: string, method: string = "GET") {
  console.log(url, method);
}
ajax("/users");

3️⃣ Function type declaration ​

Define function type

ts
type GetUsernameFunction = (x: string, y: string) => string;
let getUsername: GetUsernameFunction = function (firstName, lastName) {
  return firstName + lastName;
};
ts
type Fn = (a: number, b: number) => number;

const add: Fn = (a, b) => a + b;

4️⃣ Remaining parameters ​

ts
function sum(...numbers: number[]) {
  return numbers.reduce((val, item) => (val += item), 0);
}
console.log(sum(1, 2, 3));

5️⃣ Function overloading ​

  • Overloading in Java refers to two or more functions with the same name but different parameters.
  • In TypeScript, this is represented by providing multiple function type definitions for the same function.
ts
let obj: any = {};
function attr(val: string): void;
function attr(val: number): void;
function attr(val: any): void {
  if (typeof val === "string") {
    obj.name = val;
  } else {
    obj.age = val;
  }
}
attr("hahaha");
attr(9);
attr(true);
console.log(obj);

6. Union type & type alias (very commonly used) ​

1️⃣ Union type (|) ​

  • Union Types indicate that the value can be one of multiple types
  • When not assigned, only properties and methods common to both types can be accessed on the union type.
ts
let name: string | number;
console.log(name.toString());
name = 3;
console.log(name.toFixed(2));
name = "hello ";
console.log(name.length);

export {};
ts
let id: number | string;

id = 1;
id = "1";

2️⃣ type (type alias) ​

ts
type ID = number | string;

type User = {
  id: ID;
  name: string;
};

7. any / unknown (must understand) ​

1️⃣ any (not recommended) ​

  • any means it can be assigned to any type
  • You can use any when the third-party library does not provide a type file
  • When type conversion encounters difficulties
  • Data structures are too complex to define
ts
let a: any = 1;
a.foo.bar(); // TS 不管,运行时可能炸
ts
let root: any = document.getElementById("root");
root.style.color = "red";
ts
let root: HTMLElement | null = document.getElementById("root");
root!.style.color = "red"; //非空断言操作符

2️⃣ unknown (security version any) ​

ts
let x: unknown;

if (typeof x === "string") {
  x.toUpperCase(); // ✅
}

👉 Rule of Thumb

  • If you can use any, don’t use it.
  • Interface data is uncertain → unknown + 类型守卫

8. null and undefined ​

  • null and undefined are subtypes of other types and can be assigned to other types, such as numeric types. In this case, the assigned type will become null or undefined
  • The strictNullChecks parameter is used in the new strict null check mode. In the strict null check mode, null and undefined values do not belong to any type. They can only be assigned to their own type or any
ts
let x: number;
x = 1;
x = undefined;
x = null;

let y: number | null | undefined;
y = 1;
y = undefined;
y = null;

9. void type ​

  • void means there is no type
  • When a function does not return a value, TS will assume that its return value is of type void.
ts
function greeting(name: string): void {
  console.log("hello", name);
  //当我们声明一个变量类型是 void 的时候,它的非严格模式(strictNullChecks:false)下仅可以被赋值为 null 和 undefined
  //严格模式(strictNullChecks:true)下只能返回undefined
  //return null;
  //return undefined;
}

10. Special types ​

1️⃣ never type ​

  • As the return value type of a function that does not return ( return )
ts
// 返回never的函数 必须存在 无法达到( unreachable ) 的终点
function error(message: string): never {
  throw new Error(message);
}
let result1 = error("hello");
// 由类型推论得到返回值为 never
function fail() {
  return error("Something failed");
}
let result = fail();

// 返回never的函数 必须存在 无法达到( unreachable ) 的终点
function infiniteLoop(): never {
  while (true) {}
}

2️⃣ strictNullChecks ​

  • In TS, null and undefined are valid values of any type, so there is no way to properly detect whether they are being used incorrectly.So TS introduced the --strictNullChecks checking mode
  • Thanks to the introduction of --strictNullChecks, null and undefined can be detected in this mode.So TS needs a new bottom type.So never was introduced.
ts
// Compiled with --strictNullChecks
function fn(x: number | string) {
  if (typeof x === "number") {
    // x: number 类型
  } else if (typeof x === "string") {
    // x: string 类型
  } else {
    // x: never 类型
    // --strictNullChecks 模式下,这里的代码将不会被执行,x 无法被观察
  }
}

3️⃣ The difference between never and void ​

  • void can be assigned to null and undefined types.never is a type that does not contain a value.
  • Functions with a void return value type work fine.Functions with a never return type cannot return normally, cannot be terminated, or may throw an exception.

11. Symbol ​

  • When we use Symbol, we must add the es6 compilation auxiliary library
  • Symbol is a new primitive type after ES2015, which is created through the Symbol constructor
  • The value of Symbol is the only constant
ts
const sym1 = Symbol("key");
const sym2 = Symbol("key");
Symbol("key") === Symbol("key"); // false

12. BigInt ​

  • Use BigInt to safely store and manipulate large integers
  • When we use BigInt, we must add the ESNext compilation auxiliary library
  • To use 1n requires "target": "ESNext"
ts
// number和 BigInt类型不一样,不兼容
const max = Number.MAX_SAFE_INTEGER; // 2**53-1
ts
console.log(max + 1 === max + 2);
const max = BigInt(Number.MAX_SAFE_INTEGER);
ts
console.log(max + 1n === max + 2n);
let foo: number;
let bar: bigint;
foo = bar;
bar = foo;

13. Type derivation (the “intelligence” of TS) ​

  • It refers to the ability of a programming language to automatically deduce the type of a value. It is a feature that appears in some strongly statically typed languages.
  • If no value is assigned during definition, it will be inferred to be an any type.
  • If you assign a value when defining, you can take advantage of type inference.
ts
let num = 1; // 推导为 number
let str = "abc"; // 推导为 string

Function return values can also be deduced:

ts
function add(a: number, b: number) {
  return a + b; // 自动推导 number
}

👉 Correct posture for writing TS

  • If you can deduce it, don’t write it.
  • Clearly write external API/function boundaries

14. Assertion (you “know better than TS”) ​

  • Type assertions can specify a union type variable as a more specific type
  • Union type cannot be asserted to a non-existent type
ts
let name: string | number;
console.log((name as string).length);
console.log((name as number).toFixed(2));
console.log(name as boolean);

double assertion

ts
interface Person {
  name: string;
  age: number;
}
const person = "hello " as any as Person; // ok

1️⃣ Type inference (the soul of TS) ​

ts
let num = 1; // 自动推断为 number

❗Don’t write the type if you can’t write it

2️⃣ Type assertion (as) ​

ts
const img = document.querySelector("img") as HTMLImageElement;

⚠️ Assertion ≠ Conversion Just tell TS "I know better than you"

⚠️ Use with caution, assertion ≠ type checking

15. Literal types and type literals ​

  • The literal type must correspond one-to-one with the actual value literal. If they are inconsistent, an error will be reported.
  • The syntax of type literals and object literals is very similar
ts
const up: "Up" = "Up";
const down: "Down" = "Down";
const left: "Left" = "Left";
const right: "Right" = "Right";
type Direction = "Up" | "Down" | "Left" | "Right";
function move(direction: Direction) {}
move("Up");
ts
type Person = {
  name: string;
  age: number;
};

16. String literals vs union types ​

  • The string literal type is used to constrain that the value can only be one of several strings, and the union type (Union Types) indicates that the value can be one of multiple types.
  • String literals limit the place where the literal is used to only accept specific values. Union types do not limit values, but only limit the types of values to be consistent.

17. Typical usage of TS in front-end frameworks ​

React Props ​

ts
interface Props {
  title: string
  count?: number
}

function MyComp({ title, count = 0 }: Props) {
  return <div>{title} {count}</div>
}

Vue3 + defineProps ​

ts
interface Props {
  msg: string;
}

const props = defineProps<Props>();