xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript Cheat Sheets All In One

TypeScript Cheat Sheets All In One

TypeScript 速查表 / TypeScript 备忘单

https://www.typescriptlang.org/cheatsheets

TypeScript Cheat Sheets PDFs

.pdf

https://cdn.xgqfrms.xyz/TypeScript-Cheat-Sheets/index.html

https://cdn.xgqfrms.xyz/TypeScript-Cheat-Sheets/TypeScript Types.pdf

https://cdn.xgqfrms.xyz/TypeScript-Cheat-Sheets/TypeScript Classes.pdf

https://cdn.xgqfrms.xyz/TypeScript-Cheat-Sheets/TypeScript Interfaces.pdf

https://cdn.xgqfrms.xyz/TypeScript-Cheat-Sheets/TypeScript Control Flow Analysis.pdf

Download PDFs and PNGs

To read later or print

pdf support copy to text

https://www.typescriptlang.org/assets/typescript-cheat-sheets.zip

Types

Full name is type alias and are used to provide names to type literals Supports more rich type-system features than interfaces.

Type vs Interface

  1. Interfaces can only describe object shapes;
  2. Interfaces can be extended by declaring it mutliple times;
  3. In performance critical types interface comparison checks can be faster;

🚀: 如果能使用接口的就优先使用类型接口;不能使用的接口的才考虑使用类型字面量

Think of Types Like Variables

Much like how you can create variables with the same name in different scopes, a type has similar semantics.

Build with Utility Types

TypeScript includes a lot of global types which will help you do common tasks in the type system.
Check the site for them.

Object Literal Syntax

Terser for saving space, see Interface Cheat Sheet for more info, everything but ‘static’ matches.

type JSONResponse = {
  // Field
  version: number;
  /** In bytes */
  // Attached docs
  payloadSize: number;
  // Optional
  outOfStock?: boolean;
  // Arrow func field
  update: (retryTimes: number) => void;
  // ES5 Function
  update(retryTimes: number): void;
  // Type is callable
  (): JSONResponse;
  // Accepts any index
  [key : string]: number;
  // Newable
  new (s: string): JSONResponse;
  // Readonly property
  readonly body: string;
}

  1. Object Literal Type
type Location = {
  x: number;
  y: number;
};
  1. Primitive Type

Useful for documentation mainly

type MissingNo = 404;
type SanitizedInput = string;

  1. Tuple Type

A tuple is a special-cased array with known types at specific indexes.

type Data = [
 location: Location,
 timestamp: string,
];
  1. Union Type

Describes a type which is one of many options, for example a list of known strings.

type Size = "small" | "medium" | "large"
  1. Intersection Types

A way to merge/extend types.

type Location = { x: number } & { y: number }
// { x: number, y: number }
  1. Type Indexing

A way to extract and name from a subset of a type.

type Response = { data: { ... } }

type Data = Response["data"]
 // { ... }
  1. Type from Value

Re-use the type from an existing JavaScript runtime value via the typeof operator.

const data = { ... }
type Data = typeof data;

  1. Type from Function Return

Re-use the return value from a function as a type.

const createFixtures = () => { ... }
type  Fixtures = ReturnType<typeof createFixtures>

function test(fixture: Fixtures) { ... }
  1. Type from Module
const Data: import( "./data" ).data;

These features are great for building libraries, describing existing JavaScript code and you may find you rarely reach for them in mostly TypeScript applications.

  1. Mapped Types

Acts like a map statement for the type system, allowing an input type to change the structure of the new type.

type Artist = { name: string, bio: string }

// Loop through each field in the type generic parameter “Type”
type Subscriber<Type> = {
  // Sets type as a function with original type as param
  [Property in keyof Type]: (newValue: Type[Property]) => void
}

type ArtistSub = Subscriber<Artist>

/* 
type ArtistSub = {
    name: (newValue: string) => void;
    bio: (newValue: string) => void;
}
 */

https://www.typescriptlang.org/play?#code/C4TwDgpgBAggTsAlgZ2FAvFA3lAdgQwFsIAuKVORXAcwBooAjRAezIquqgF8AoHgen5QAMs2ZgowABZxmAV2pSoEfAGMlAM0QQANgBMoVSVOihIUahFwRKqqGHxwiEYDaiAcAgAq4CIFwCHmbQAMpyDMiqlAw2ADzekAB8GNg8UFCCUEEuyJI+UPjZ+FAacriqSMy4UADuiNJQzJTUVPg6Oeb59o5EKVAA2gAKspAIIIaVANYQIMwaUHEQALpkABTWVQBqLXKkcz4DQzagCwCUGIkAbsyIejy8AbnwSKghDEkv4ZExjyjA8Xz8ACooHxArAED8XkksD1UgRiCs1psdNs2MBKDRTugLlc9ABuGGMFgIiAbLY7dgYs5QS7XfG8KAA-hAA

  1. Conditional Types

Acts as “if statements” inside the type system.
Created via generics, and then commonly used to reduce the number of options in a type union.

type Bird = {legs : 2 }
type Dog = {legs : 4 }
type Ant = {legs : 6 }
type Wolf = {legs : 4 }
// Union
type Animals = Bird | Dog | Ant | Wolf;

type HasFourLegs<Animal> = Animal extends {legs : 4 } ? Animal : never

type FourLegs = HasFourLegs<Animals>
// type FourLegs = Dog | Wolf

https://www.typescriptlang.org/play?ssl=12&ssc=30&pln=1&pc=1#code/C4TwDgpgBAQglgJwCZQLxQN4BsIHMDOUAXFAExQC+AUKJFACID2uamOBxUALJTeNAEEAdsFbY8hEgDZetaAHVGWAGZj2k7rwD0WqAFUhcRkL51hcALYBDLIXTxkUAD4NmzqMNEvFKgNxVTaAAJK3wAMUYAVwQAGQkAHnNrLAA+ViSbKAgAD2AIISRCcQ4SHgooAH4PQ2TOIQgANwgEALkoCOi4jnQQ8KjYhIzbFICdKDaOge7XFm8lZSA

  1. Template Union Types

A template string can be used to combine and manipulate text inside the type system.

type SupportedLanguages = "en" | "pt" | "zh";
type FooterLocaleIDs = "header" | "footer";

type AllLocaleIDs = `${SupportedLanguages}_${FooterLocaleIDs}_id`;

/* 

type AllLocaleIDs = "en_header_id" | "en_footer_id" | "pt_header_id" | "pt_footer_id" | "zh_header_id" | "zh_footer_id"

 */

https://www.typescriptlang.org/play?#code/C4TwDgpgBAygrmMB7ATsCATAMgQwHYDmcOBEAzlALxQBEEeNUAPrWMIyzQF4AWNA3AChQkKADEkSdCixIAxjgA2EAJIARCtRo8IODBBQdaAM0nSBg4eGgBBRYtkLl6zVAAGAEgDe8RKnTY+EQk5AC+APreElIGjkqqGhEAlhhuQoIA9ABUUJYitvZxzhpUtPThOnoG4SlGdHjhpjEoNRh1bBW6+i21zKzAjWbVvZy8nVU9bX3cPIPNrTSWUFkZQA

Classes

A TypeScript class has a few type-specific extensions to ES2015 JavaScript classes, and one or two runtime additions.

Creating an class instance

Parameters to the new ABC come from the constructor function.

class ABC { ... }
const abc = new ABC()

private x vs #private

The prefix private is a type-only addition, and has no effect at runtime.
Code outside of the class can reach into the item in the following case:

// TS private type ❌ type check 私有属性
class Bag {
  private item: any
}

Vs #private which is runtime private and has enforcement inside the JavaScript engine that it is only accessible inside the class:

// ESM #private ✅ 真正的私有属性
class Bag {
  #item : any
}

this in classes (基于 prototype 原型链的类继承)

The value of this inside a function depends on how the function is called.
It is not guaranteed to always be the class instance which you may be used to in other languages.

You can use this parameters, use the bind function, or arrow functions to work around the issue when it occurs.

Type and Value

Surprise, a class can be used as both a type or a value.
令人惊讶的是,既可以用作类型也可以用作

//       ⬇Type       ⬇Value
const a:Bag = new Bag()

So, be careful to not do this:

class C implements Bag {}
  1. Common Syntax
// Subclasses this class
// Ensures that the class conforms to a set of interfaces or types
class User extends Account implements Updatable, Serializable {
  // A field
  id: string;
  // An optional field / 可选属性
  displayName?: boolean;
  // A ‘trust me, it’s there’ field / 强制类型断言
  name!: string;
  //  A private field
  #attributes: Map<any, any>;
  // A field with a default
  roles = ["user"];
  // A readonly field with a default
  readonly createdAt = new Date()
  // The code called on ‘new’

  constructor(id: string, email: string) {
    super(id);
    // In this code is checked against the fields to ensure it is set up correctly
    this.email = email;
    // ...
  }

  // Ways to describe class methods (and arrow function fields)
  setName(name: string) { this.name = name }
  verifyName = (name: string) => { ... }

  // A function with 2 overload definitions
  sync(): Promise<{ ... }>
  sync(cb: ((result: string) => void)): void
  sync(cb?: ((result: string) => void)): void | Promise<{ ... }> { ... }

  // Getters and setters
  get accountID() { } 
  set accountID(value: string) { }

  // Private access is just to this class, protected allows to subclasses. 
  // Only used for type checking, public is the default.
  private makeRequest() { ... }
  protected handleRequest() { ... }

  // Static fields / methods
  static #userCount = 0;
  static registerUser(user: User) { ... }

  // Static blocks for setting up static vars. ‘this’ refers to the static class
  static { this.#userCount = -1 }
  // ...
}

  1. Generics

Declare a type which can change in your class methods.

// Class type parameter
class Box<Type> {
  contents: Type
  // Used here
  constructor(value: Type) {
   this.contents = value;
  }
}

const stringBox = new Box( )

These features are TypeScript specific language extensions which may never make it to JavaScript with the current syntax.

  1. Parameter Properties

A TypeScript specific extension to classes which automatically set an instance field to the input parameter.

class Location {
 constructor (public x: number, public y: number) {
   //
 }
}

const loc = new Location(20, 40);
loc.x
// 20
loc.y
// 40
  1. Abstract Classes

A class can be declared as not implementable, but as existing to be subclassed in the type system.
As can members of the class.

类可以声明不可实现,但可以在类型系统中作为子类存在。
类成员也可以。

abstract class Animal {
 abstract getName(): string;
 printName () {
   console.log("Hello, " + this.getName());
 }
}

class Dog extends Animal {
  getName(): { ... }
}

  1. Decorators and Attributes

You can use decorators on classes, class methods, accessors, property and parameters to methods.
您可以在类、类方法、访问器、属性和方法参数上使用装饰器

import {
  Syncable, triggersSync, preferCache, required
} from "mylib"

@Syncable
class User {
 @triggersSync()
 save() { ... }
 @preferCache (false)
 get displayName() { ... }
 update(@required info: Partial<User>) { ... }
}

Interfaces

Used to describe the shape of objects, and can be extended by others.
Almost everything in JavaScript is an object and interface is built to match their runtime behavior.

Built-in Type Primitives

js: boolean, string, number, undefined, null, bigint, symbol,
ts: any, unknown, never, void

Common Built-in JS Objects

Date, Error, Array, Map, Set, Regexp, Promise

Type Literals

Object: { field: string }
Function: (arg: number) => string
Arrays: string[] or Array<string>
Tuple: [string, number]

Avoid ⚠️

Object, String, Number, Boolean

  1. Common Syntax
// Optionally take properties from existing interface or type
interfaceJSONResponse extends Response, HTTPAble {
  version: number;
  // JSDoc comment attached to show in editors
  /** In bytes */
  payloadSize: number;
  // This property might not be on the object
  outOfStock?: boolean;
  // These are two ways to describe a property which is a function
  // ES6 箭头函数
  update: (retryTimes: number) => void;
  // ES5 function
  update (retryTimes: number): void;
  // You can call this object via () - ( functions in JS are objects which can be called )
  (): JSONResponse
  // You can use new on the object this interface describes
  new (s: string): JSONResponse;
  // Any property not described already is assumed to exist, and all properties must be numbers
  [key: string]: number;
  // Tells TypeScript that a property can not be changed
  readonly body: string;
}

  1. Generics

Declare a type which can change in your interface

// Type parameter
interface APICall<Response> {
 data: Response
}

const api: APICall<ArtworkCall> = ...
api.data
// Artwork

You can constrain what types are accepted into the generic parameter via the extends keyword.

// Sets a constraint on the type which means only types with a ‘status’ property can be used
interface APICall<Response extends { status: number }> {
  data: Response
}

const api: APICall<ArtworkCall> = ...
api.data.status

  1. Overloads

A callable interface can have multiple definitions for different sets of parameters

interface Expect {
  (matcher: boolean): string;
  (matcher: string): boolean;
}

  1. Get & Set

Objects can have custom getters or setters

interface Ruler {
 get size(): number
 set size(value: number | string);
}

// Usage
const r: Ruler = {size: 0}
r.size = 12
r.size = "36"

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgEoFcA21kG8BQyA5hGMgM7ABeEAFAJQBcyI6AtgEbSHmkXV0AbnEzoIzVpxwAfCmCigi9ANz4AvvnwB6LcgCq5OCXwIA9iHJkozDNijIAvHko1mABg1QAdC5ROAjABM+N6+jsgARADMAGwRQA

  1. Extension via merging / 通过合并扩展

Interfaces are merged, so multiple declarations will add new fields to the type definition.

interface APICall {
  data: Response
}

interface APICall {
  error?: Error
}

// class API implements APICall {
//   data: Response
//   error?: Error|undefined
// }

https://www.typescriptlang.org/play?ssl=12&ssc=5&pln=9&pc=1#code/JYOwLgpgTgZghgYwgAgIIAUCSBhOAbPZAbwChlkATOMOALmQCUIBnABwHsRmISBfEkqEixEKDDnyFS5aFHZQA-PQCiUOVD4CA9FuQI8cZszRZkwALas8EcxHDHxuAsRI7ylanUYsOXHm5k1eSVkVXUAHwBXEAoIGFAIClddXiA

  1. Class conformance / 类别一致性

You can ensure a class conforms to an interface via implements:

interface Syncable { sync(): void }

class Account implements Syncable {
  // ...
}

Control Flow Analysis / 控制流分析

CFA

CFA nearly always takes a union and reduces the number of types inside the union based on logic in your code.
A function with a return type describing the CFA change for a new scope when it is true.
A function describing CFA changes affecting the current scope, because it throws instead of returning false.

Most of the time CFA works inside natural JavaScript boolean logic, but there are ways to define your own functions which affect how TypeScript narrows types.

CFA 几乎总是采用联合类型并根据代码中的逻辑减少联合内的类型数量
具有返回类型的函数,描述当它为 true 时 CFA 对新范围的更改。
描述影响当前范围的 CFA 更改的函数,因为它抛出而不是返回 false。

大多数时候,CFA 在原生 JavaScript 布尔逻辑内工作,但有一些方法可以定义您自己的函数,这些函数会影响 TypeScript 缩小类型的方式。

  1. type guards / 类型守卫

A function with a return type describing the CFA change for a new scope when it is true.

// is 类型谓词
// Return type position describes what the `assertion` is
function isErrorResponse(obj: Response): obj is APIErrorResponse {
  return obj instanceof APIErrorResponse
}

// Usage
const response = getResponse();
response
// Response | APIErrorResponse

if (isErrorResponse(response)) {
  response
 // APIErrorResponse
}

type predicates / 类型谓词

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates

  1. Assertion Functions / 断言函数

A function describing CFA changes affecting the current scope, because it throws instead of returning false.

// asserts 断言
function assertResponse(obj: any): asserts obj is SuccessResponse {
  if (!(obj instanceof SuccessResponse)) {
    throw new Error(“Not a success!”)
 }
}

// Usage
const res = getResponse()
res
// SuccessResponse | ErrorResponse

assertResponse(res)
// Assertion functions change the current `scope` or `throw`
res
// SuccessResponse

// interface SuccessResponse {
//   code: number;
//   data: Object;
//   status: string;
// }

// const SuccessResponse = {
//   code: 200,
//   data: {},
//   status: "success",
// }
  1. Assignment

Narrowing types using as const

Subfields in objects are treated as though they can be mutated, and during assignment the type will be ‘widened’ to a non-literal version. The prefix as const locks all types to their literal versions.

const data1 = {
  name: "xgqfrms"
}
/* 
const data1: {
    name: string;
}
 */

type D1 = typeof data1
/* 
type D1 = {
    name: string;
}
 */


const data2 = {
  name: "xgqfrms"
} as const
/* 
const data2: {
    readonly name: "xgqfrms";
}
 */

type D2 = typeof data2
/* 
type D2 = {
    readonly name: "xgqfrms";
}
 */

https://www.typescriptlang.org/play?ssl=32&ssc=4&pln=1&pc=1#code/MYewdgzgLgBAJgQyggjDAvDA3gWAFAwxgIC2ApgFwwBEAHgOYCOAZgE4kTX4C++A9ACoY+UJFiJkKKrgKEipSjGisAlmHoBuHvhgC++fFACeABzIwAImkzGzIZvCSp+Qw6fNWM2HXOLkqymqa2gR6Bngi4NCOyABMXjKEfop0TGwcXHjcMAgQMKLQLsJ4BeJOsdI+hKxkCHDgADZG8v40DCzsnFpZOmEReLYe8Tbu9jEIsUVuZpbD3rLVtfVgTS0p7eldIbp8QA

Tracks through related variables

const response = getResponse()
const isSuccessResponse = res instanceof SuccessResponse;

if (isSuccessResponse) {
 res.data
 // SuccessResponse
}

Re-assignment updates types

let data: string | number = ...
// string | number

data = "Hello"
// string
  1. Discriminated Unions
// All members of the union have the same property name, CFA can discriminate on that.
type Responses =
  | { status: 200, data: any }
  | { status: 301, to: string }
  | { status: 400, error: Error }

const response = getResponse()
response
// Responses

switch(response.status) {
 case 200:
   return response.data
 case 301:
   return redirect(response.to)
 case 400:
   return response.error
}

  1. If Statements

Most narrowing comes from expressions inside if statements, where different type operators narrow inside the new scope

typeof (for primitives)

const input = getUserInput()
input
// string | number

if (typeof input === "string") {
  input
  // string ✅
}

instanceof (for classes)

const input = getUserInput()
input
// string | number []

if (input instanceof Array) {
  input
  // number[] ✅
}

property in object (for objects)

const input = getUserInput()
input
// string | { error: ... }
if ("error" in input) {
  input
  // { error: ... } ❌
}

type-guard functions (for anything)

const input = getUserInput()
input
// string | number []

if (Array.isArray(input)) {
  input
  // number[] ✅
}

Expressions

Narrowing also occurs on the same line as code, when doing boolean operations

const input = getUserInput()
input
// string | number

const inputLength = (typeof input === "string" && input.length) || input
// input: string

https://www.typescriptlang.org/play?#code/Q

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

TypeScript: TS Playground

An online editor for exploring TypeScript and JavaScript

https://www.typescriptlang.org/play?#code/Q

refs

advanced types

https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types
https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-02-10 01:07  xgqfrms  阅读(135)  评论(3编辑  收藏  举报